Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.