Apr 13, 2016

Difference between save(), saveOrUpdate() and persist() in Hibernate Session

save()/ saveOrUpdate()/persist(), these methods are present in Hibernates’s Session interface. These methods serves the purpose of moving object’s state from new/transient to persistent state. However there are some differences between these 3 three APIs – one of popular interview question if you are a java developer. This post aims at listing out these differences.

save() vs saveOrUpdate() vs Persist()

1) Session.save() – It performs an INSERT operation, i.e., persists object in the database and returns the identifier of the persisted entity.
saveOrUpdate() – In case there is a detached object in the Hibernate Session that needs to be re-attached, saveOrUpdate() method can be used. It can perform INSERT or UPDATE operation for an object, hence the API name (saveOrUpdate).
persist() – Similar to Session.save() i.e., it is used to move a transient object to the persistent state by storing it into the database but it doesn't return the database identifier.

2) Second difference is the consequence of what we discussed in first point. As already said,
save() does an INSERT operation, which means if the primary key already exists in the database, INSET operation will fail.
On the other hand, saveOrUpdate()performs INSERT or UPDATE operation. It first executes the SELECT query to see if there exists any identifier in the database corresponding to one in the object being persisted, if any found, UPDATE query is executed.
That is why save() should only be called with new object only. It will fail if called on detached objects.

3) Another difference is that persist() and saveOrUpdate() method’s return type is void whereas save() returns the identifier of the persisted entity. See below for the method signatures of the three:
public Serializable save(Object object) throws HibernateException
public void saveOrUpdate(Object object) throws HibernateException
public void persist(Object object) throws HibernateException

That’s it! Use the save() method to store new object into database and if you don’t need the identifier generated, use persist() method. SaveOrUpdate() method should be used to persist detached object’s.

If liked the article, you can join us @ +Java Territory to stay updated.


Post a Comment