Home > Java > Hibernate hard facts – Part 7

Hibernate hard facts – Part 7

In the seventh article of this serie, we’ll have a look at the difference between saveOrUpdate() and merge().

Update

Hibernate’s way for updating entities is through the update() method. Wa can get an object, detach it from the session and then update it later with no problem. The following snippet shows how it works:

Session session = factory.getCurrentSession();

Customer customer = (Customer) session.get(Customer.class, 1L);

session.getTransaction().commit();

customer.setFirstName("John");

beginTransaction();

session = factory.getCurrentSession();

session.update(customer);

This will issue a SQL’s UPDATE statement.

However, update()‘s Javadoc states that “If there is a persistent instance with the same identifier, an exception is thrown”.

This means that loading the same customer just before the update (and after the transaction’s beginning) will miserably fail – with a NonUniqueObjectException.

Session session = factory.getCurrentSession();

Customer customer = (Customer) session.get(Customer.class, 1L);

session.getTransaction().commit();

customer.setFirstName("John");

beginTransaction();

session = factory.getCurrentSession();

session.get(Customer.class, 1L);

// Fail here

session.update(customer);

Merge

Merging is a feature brought by Hibernate 3, inspired by JPA. Whereas update conflicts if the same entity is already managed by Hibernate, merge also copies the changes made to the detached entity so there’s no exception thrown.

Session session = factory.getCurrentSession();

Customer customer = (Customer) session.get(Customer.class, 1L);

session.getTransaction().commit();

customer.setFirstName("John");

beginTransaction();

session = factory.getCurrentSession();

session.get(Customer.class, 1L);

// Succeeds!

session.merge(customer);

As opposed to update, note that merge doesn’t associate the detached instance to Hibernate’s memory store but returns a new instance that’s in it instead. Further operations should be made to the returned instance.

Conclusion

When in a web context, detached entities are everywhere.  Most of the time, update() should be enough to do the trick. When not, think about merge() but keep in mind to use the returned instance.

Finally, if the entity cannot be reconstructed – because some attributes are missing from the web page – the best strategy is to load the entity from the database and then modify its attributes as needed. In this case, there’s no need to update nor merge: the statement will be executed during session flush.

You can download sources for this article here in Maven/Eclipse format.

email
Send to Kindle
Categories: Java Tags:
  1. Abdellah
    June 6th, 2011 at 10:15 | #1

    I have the feeling that merge is a new version of “update” and it’s safer to use it in all cases because you won’t get any exception thrown

  1. No trackbacks yet.