Can anyone tell me what's the advantage of persist()
vs save()
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.
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.
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.
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.
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 withpersist()
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With