Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between session.persist() and session.save() in Hibernate?

Tags:

java

hibernate

Can anyone tell me what's the advantage of persist() vs save() in Hibernate?

like image 583
Antonio Avatar asked Oct 16 '22 08:10

Antonio


People also ask

What is the difference between Save () and persist () method in hibernate?

Difference between save and persist method in Hibernate First difference between save and persist is there return type. Similar to save method persist also INSERT records into database but return type of persist is void while return type of save is Serializable object.

What is Session persist in hibernate?

Hibernate persist is similar to save (with transaction) and it adds the entity object to the persistent context, so any further changes are tracked. If the object properties are changed before the transaction is committed or session is flushed, it will also be saved into database.

What is Session Save method?

The save() method is used make a TRANSIENT entity PERSISTENT by associating it with either an org. hibernate. Session . Before persisting the entity, it assigns a generated identifier to the ID field.

What is the difference between save and merge 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

From this forum post

persist() is well defined. It makes a transient instance persistent. However, it doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. The spec doesn't say that, which is the problem I have with persist().

persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. This is useful in long-running conversations with an extended Session/persistence context.

A method like persist() is required.

save() does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier (e.g. "identity" generator, not "sequence"), this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is not good in a long-running conversation with an extended Session/persistence context.

like image 166
Bala R Avatar answered Oct 17 '22 22:10

Bala R