What's the difference between session.persist() and session.save() in Hibernate?
Solution 1:
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.
Solution 2:
I have done good research on the save() vs. persist() including running it on my local machine several times. All the previous explanations are confusing and incorrect. I compare save() and persist() methods below after a thorough research.
Save()
- Returns generated Id after saving. Its return type is
Serializable
; - Saves the changes to the database outside of the transaction;
- Assigns the generated id to the entity you are persisting;
-
session.save()
for a detached object will create a new row in the table.
Persist()
- Does not return generated Id after saving. Its return type is
void
; - Does not save the changes to the database outside of the transaction;
- Assigns the generated Id to the entity you are persisting;
-
session.persist()
for a detached object will throw aPersistentObjectException
, as it is not allowed.
All these are tried/tested on Hibernate v4.0.1
.