Difference between save and saveOrUpdate in Hibernate

What is difference between save and saveOrUpdate 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 saveOrUpdate in Hibernate.

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

Difference between save and saveOrUpdate in Hibernate

Create a program for testing save method

Run above main and produce the output like below

Create a program for testing saveOrUpdate method

Run above main and print the output like this:

In 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 saveOrUpdate method again, here the update query is executed since the data exists.

Difference between save and saveOrUpdate in Hibernate

Main difference between save and saveOrUpdate method is that save() generates a new identifier and INSERT record into database while saveOrUpdate can either INSERT or UPDATE based upon existence of record. If object already exists in the database, save() method will fail.

The save() method returns the identifier generated by the database. On the other hand, saveOrUpdate() can do INSERT or UPDATE depending upon whether object exists in database or not. saveOrUpdate does a select first to determine if it needs to do an insert or an update.

Another key difference between save() and saveOrUpdate() method is that save() method is used to make a transient object to persistent state but saveOurUpdate() can make both transient (new object) and detached (existing object) object into persistent state. So that saveOrUpdate() is often used to re-attach a detached object into Session.

That’s it on the difference between save and saveOrUpdate in Hibernate tutorial.

Download complete source code, please click link below

SaveAndSaveOrUpdate.zip (48 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons