0
Sponsored Links


Ad by Google
Nowadays ORM framework is on demand. In J2EE interview, hibernate interview questions are also play a very important role.

In my previous post we have seen evergreen hibernate interview question Difference between get() and load() method and here we are going to see another most popular hibernate interview question "Difference between save and persist method in hibernate"

In short you can say both methods are used to create records inside database. Both methods are available inside Session interface, below are the key differences between session.save() and session.persist(). From here you can find all the core classes and interfaces of hibernate 4

Differences:
  1. Return type of save() is Serializable. Here is complete signature of save() method, Serializable save(Object object) throws HibernateException. Whereas return type of persist() is void. Here is complete signature of persist() method, void persist(Object object) throws HibernateException
  2. The persist() makes a transient instance persistent. However, it does not guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. Whereas save() makes a transient instance persistent, and does guarantee to return an identifier. If an INSERT has to be executed to get the identifier ( e.g. "identity" generator, not "sequence"), this INSERT happens immediately.
  3. The 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. Whereas save() INSERT happens immediately, no matter if you are inside or outside of a transaction. This is problematic in a long-running conversation with an extended Session/persistence context.


How to use:

long id = session.save(user);

session.persist(user); // this must be in transaction block




That's it :)

Sponsored Links

0 comments:

Post a Comment