Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate saveOrUpdate behavior

Does anyone know how Hibernate knows whether to INSERT or to UPDATE a value in the database when session.saveOrUpdate() is called?

So far, I have only determined that it is not dependent on the information in the cache, and that the existence of the entity in the database is determined by the primary key.

like image 604
iliaden Avatar asked Jun 22 '11 17:06

iliaden


People also ask

How does saveOrUpdate work in hibernate?

saveOrUpdate() Hibernate will check if the object is transient (it has no identifier property) and if so it will make it persistent by generating it the identifier and assigning it to session. If the object has an identifier already it will perform .

What is difference between hibernate save () saveOrUpdate () and persist () methods?

Difference between save and saveOrUpdate in Hibernatesave() generates a new identifier and INSERT record into the database while saveOrUpdate can either INSERT or UPDATE based upon the existence of a record.

What is the return type of saveOrUpdate in hibernate?

It returns the id of the entity created. The saveOrUpdate() calls either save() or update() on the basis of identifier exists or not. e.g if identifier does not exist, save() will be called or else update() will be called.

What is difference between Merge and saveOrUpdate in hibernate?

Once save/update is done, the object DOES NOT reflect the change. The returned object reflects the changes, and it is attached to hibernate session. MERGE method offers greater flexibility when it comes to saving data objects, since you need not worry about attaching object to Session.


1 Answers

When you use .saveOrUpdate() Hibernate will check if the object is transient (it has no identifier property) and if so it will make it persistent by generating it the identifier and assigning it to session. If the object has an identifier already it will perform .update().

From the documentation:

saveOrUpdate() does the following:

  • if the object is already persistent in this session, do nothing
  • if another object associated with the session has the same identifier, throw an exception
  • if the object has no identifier property, save() it
  • if the object's identifier has the value assigned to a newly instantiated object, save() it
  • if the object is versioned by a "version" or "timestamp", and the version property value is the same value assigned to a newly instantiated object, save() it otherwise update() the object
like image 143
Rihards Avatar answered Sep 23 '22 12:09

Rihards