nKognito
nKognito

Reputation: 6363

Hibernate: the best way to update an object

lets's say I have:

// all objects have valid mapping to database
public class A {
   private int id;
   private String name;
   private List<B> chidlren1;
   private List<C> children2;
}

in my controller's update method i have to update a specific object, but new values for it I store in session variable like another A object.

So the question is what valid way to update that specific object from another object? Is the next code valid?

A old = dao.get(id);
A temp = getFromSession();

old.Name = temp.Name;
old.Children1 = temp.Children1;
old.Children2 = temp.Children2;
dao.update(old);

And another question - if previoud method is right, will hibernate first delete all records from chidlren's tables and add a new ones or it can automatically update/insert new records and remove the deleted ones?

Thank you

UPD#1: Let's say chidlren collections of temp are different from children collections of old?

Upvotes: 4

Views: 5119

Answers (2)

A Lee
A Lee

Reputation: 8066

If the ids are set properly on your child entity collections of type A and B and you have specified cascade=MERGE on those entities you should be able to use the merge method, e.g.,

A updatedEntity = dao.merge(yourObjectFromTheHttpSession);

That said, I've had to manually reconcile related collections to properly handle new incoming entities and remove existing entities in the past and have been unable to rely on hibernate to automagically take care of everything, so YMMV.

From the docs:

Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped with cascade="merge".

The semantics of this method are defined by JSR-220.

Upvotes: 4

avastxa
avastxa

Reputation: 1

I agree with Rakesh. if you still doubtfull abort it, you can set "show_sql = true" (a hibernate propety), you will see the sql string.

Upvotes: 0

Related Questions