Difference between save and persist method in Hibernate

What is difference between save and persist method in Hibernate are most important in any Hibernate interview. Hibernate Session is the interface between java application and hibernate framework. It provides some methods to move an object from new or transient state to persistent state. For example, save(), saveOrUpdate() and persist() methods are used to store an object into database. However, they have some differences about usage.

Other interesting posts you may like

Now we will create examples to clarify the difference between save and persist method in Hibernate.

Create project directory structure
Create project directory structure
In this difference between save and persist method in Hibernate tutorial, we will create the final project directory structure like below:

Difference between save and persist method in Hibernate

Create a program for testing save method

Run above main and produce the output like below

Create a program for testing persist method

Run above main and print the output like below:

From the above output, the insert query is executed since the data doesn’t exist. Then we load that data by identifier and change information before calling the persist method again, here the update query is executed since the data exists.

Difference between save and persist method in Hibernate

First difference between save and persist is there return type. The return type of persist method is void while return type of save method is Serializable object. But bot of them also INSERT records into database

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.

Third difference between save and persist method in Hibernate is behavior on outside of transaction boundaries. persist() method will not execute an insert query if it is called outside of transaction boundaries. Because save() method returns an identifier so that an insert query is executed immediately to get the identifier, no matter if it are inside or outside of a transaction.

Fourth difference between save and persist method in Hibernate: persist method is called outside of transaction boundaries, it is useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.

Fifth difference between save and persist method in Hibernate: persist is supported by JPA, while save is only supported by Hibernate.

That’s it on the Difference between save saveOrUpdate and persist in Hibernate.

Reference
Hibernate Documentation

Download complete source code, please click link below

SaveAndPersist.zip (71 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons