Difference between save vs persist methods in Hibernate

Difference between save vs persist methods in Hibernate

Difference between save vs persist methods in Hibernate

Difference between save vs persist methods in Hibernate

session.save() method returns the generated identity value but session.persist() method doesn’t return the generated identity value because the return type is void.

Whenever we are using ORM like Hibernate, there are two from many others methods save() and persist() using to save the object in the database. But these two methods have the differences in functionality. And also the difference between hibernate save() and persist() methods depend on generator class we are using. There are following few differences as below.

  1. Suppose we are using generator class to assign the primary key to persist the object, then there is no difference between these two methods because in generating class programmer we need to give the primary key value to save in the database.
  2. Session.save() for a detached object will create a new row in the table. Session.persist() for a detached object will throw PersistentObjectException as it is not allowed.
  3. the main difference between save() and persist() is there return type. save () method return Serializable object but persist() method return void.
  4. Another difference between persist() and save() is that both methods make a transient object to persistent state. However, persist() method doesn’t guarantee that the identifier value will be assigned to the persistent state immediately, the assignment might happen at flush time.
  5. Fifth difference between save() and persist() method in Hibernate: persist is supported by JPA, while save is only supported by Hibernate.

Example:—

Leave a Reply

Your email address will not be published. Required fields are marked *

*