Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Hibernate Basics Persisting Data with Hibernate Wrap-Up

Karrtik Iyer
Karrtik Iyer
3,738 Points

Why did we have to get int ID from save?

For the update code example, we changed the code to get the ID returned from the save method. But not sure why we needed it, we had the contact object that we called save on, On that contact object we could have just used contact.getId(), isn't that possible? Please see comment below in the code.

Contact contact = new ContactBuilder("ABC", "DEF") .withEmail("abc@def.com") .withPhone(435643466L).build();

    int id = save(contact);
    System.out.println("After Saving");
    System.out.println(contact);
    System.out.println("Before Fetching All");
    //System.out.println(contact.toString());
    List<Contact> contacts = fetchAllContacts();
    for (Contact c:contacts
         ) {
        System.out.println(c);
    }
    Contact c1 = findContactById(contact.getId()); //We could do this instead of using the id returned by save, right?


    c1.setEmail("sfsdgs@sdggsdgf");
    c1.setFirstName("SomethingElse");
    update(c1);
    fetchAllContacts().stream().forEach(System.out::println);
    delete(c1);
    fetchAllContacts().stream().forEach(System.out::println);

1 Answer

Jeremiah Shore
Jeremiah Shore
31,168 Points

You appear to be correct; I think it would be okay to use getId() if you wanted to. However, if you chose to do so, it might not be as obvious to someone reading your code if your Contact object is simply named contact. Along with employing some more descriptive variable names, such as newContact and/or newlyGeneratedContactId, doing so might make your intention clearer.