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.
- 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.
- 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.
- the main difference between save() and persist() is there return type. save () method return Serializable object but persist() method return void.
- 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.
- Fifth difference between save() and persist() method in Hibernate: persist is supported by JPA, while save is only supported by Hibernate.