Difference Between Update And Saveorupdate In Hibernate

As we know that update() and merge() methods in hibernate are used to convert the object which is in detached state into persistence state. But there are different situation where we should be used update() and where should be used merge() method in hibernate, let us see below snippet of codes.

  1. Difference Between Merge And Saveorupdate In Hibernate
  2. Difference Between Update And Saveorupdate In Hibernate Windows 10
  3. Difference Between Update And Saveorupdate In Hibernate Windows 7
  4. Difference Between Save And Saveorupdate In Hibernate

In the hibernate session we can maintain only one employee object in persistent state with same primary key, while converting a detached object into persistent, if already that session has a persistent object with the same primary key then hibernate throws an Exception whenever update() method is called to reattach a detached object with a session. In this case we need to call merge() method instead of update() so that hibernate copies the state changes from detached object into persistent object and we can say a detached object is converted into a persistent object.

You should apply the differnce between save and saveOrUpdate method in your code to get the best performance: 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. So saveOrUpdate method calls save method if there is no record in database, and it calls update method if there is a record in database. Related Posts: getTransaction,beginTransaction,getIdentifier in Hibernate; CRUD operations using Hibernate+ Maven+ Oracle+ XML mapping. What is the difference between session.update(Object obj), session.merge(Object obj) and session.saveOrUpdate(Object obj) method of hibernate API? Session.update, session.merge and session.saveOrUpdate all three methods are used to update the records in database using hibernate persistence logic. In this Video, You will learn about save persist and saveorupdate methods in hibernateBelow is the GitHub link to download source:https://github.com/kishanja.

Difference Between Merge And Saveorupdate In Hibernate

Update vs saveorupdate hibernate

Hibernate handles persisting any changes to objects in the session when the session is flushed. update can fail if an instance of the object is already in the session. Merge should be used in that case. It merges the changes of the detached object with an object in the session, if it exists.

Update: Suppose we are dealing with any employee object in the same session then we should use update() or saveOrUpdate() method.

Update: if you are sure that the session does not contains an already persistent instance with the same identifier,then use update to save the data in hibernate

Saveorupdate

Merge: Suppose we are creating a session and load an employee object. Now object in session cache. If we close the session at this point and we edit state of object and tried to save using update() it will throw exception. To make object persistent we need to open another session. Now we load same object again in current session. So if we want to update present object with previous object changes we have to use merge() method. Merge method will merge changes of both states of object and will save in database.

Merge: if you want to save your modifications at any time with out knowing about the state of an session, then use merge() in hibernate.

hibernate works only with persistent entities and persistent entities are classes which are attached to any hibernate session. Please note that creating an instance of a class, you mapped with a hibernate annotations, does not automatically persist the object to the database. It must be save explicitly after attaching it to a valid hibernate session.

In this tutorial, learn to use hibernate save() and saveOrUpdate() methods under different usecases.

1. Hibernate save() method

In hibernate, we generally use one of below two versions of save() method:

Both save() methods take a transient object reference (which must not be null) as an argument. Second method takes an extra parameter ‘entityName‘ which is useful in case you have mapped multiple entities to a Java class. Here you can specify which entity you are saving using save() method.

A simple example to demo hibernate save() method.

Now let’s save this hibernate entity.

Program Output.

1.1. Calling save() method on persistent entity

We got our Employee entity saved. So easy. But in reality, it is not so simple usecase. There you may need to update again employee entity and then save again in another session. Should you call save() method again? Let’s check out.

Program Output.

Here hibernate tried to insert the entity again. Though it was failed due to primary key check, but check may not be there for other entities and you may end up with duplicate rows.

Note: While second save() method causes duplicate row in different sessions, BUT in same session they will work correct.

Look at below example.

Between

Program Output.

It’s confusing. Right? Let’s make it simple. And rule is below:

Remember that you should not call save() method on a persistent entity (entity associated with any hibernate session). Any changes done to persistent entity is automatically saved.

1.2. Changing state of persistent entity

Any change to persistent entity is saved automatically. Let’s understand this concept in simple example.

Program Output.

In above example, we made the ‘emp‘ object persistent using first save() method. Afterward when we updated the last name to ‘temp‘, an update query was executed as expected. This we verified in returned data as well. This is the correct way to work with hibernate persistent entities.

2. Hibernate saveOrUpdate() method

In discussion of save() method, we forgot about case where we had to save persistent entity in another session and that got resulted in duplicate key error. That is also a valid scenario.

To handle such cases, you must use saveOrUpdate() method. Strictly speaking, you should use saveOrUpdate() with even non-persistent entities. Personally, I do not see any harm in doing so. Though, It may make you a little bit careless. So be cautious.

2.1. Hibernate saveOrUpdate() example

Let’s see how saveOrUpdate() method can be used along with entity persisted with save() method.

Program Output.

Difference Between Update And Saveorupdate In Hibernate Windows 10

Now we are able to save the entity as well as update the entity as well using saveOrUpdate() method.

Difference Between Update And Saveorupdate In Hibernate Windows 7

Difference Between Update And Saveorupdate In Hibernate

Please remember that if you have used saveOrUpdate() method in place of save() method above, then also result would have been same. saveOrUpdate() can be used with persistent as well as non-persistent entities both. Persistent entities will get updated, and transient entities will be inserted into database.

3. Suggestion For production code – best practices

It wouldn’t be advisable to try to use above code in production code. Ideally, what you would do is pass VO object to DAO layer, load the entity from the session and update the entity with by copying VO data onto it. This means that the updates take place on a persistent object, and we don’t actually have to call Session.save() or Session.saveOrUpdate() at all.

Hibernate

Once an object is in a persistent state, Hibernate manages updates to the database itself as you change the fields and properties of the object. It’s big relief.

4. Summary

  1. Save() method stores an object into the database. It will Persist the given transient instance, first assigning a generated identifier. It returns the id of the entity created.
  2. SaveOrUpdate() calls either save() or update() on the basis of identifier exists or not. e.g if identifier does not exist, save() will be called or else update() will be called.
  3. Probably you will get very few chances to actually call save() or saveOrUpdate() methods, as hibernate manages all changes done in persistent objects.

Let me know is something is not clear or needs more explanation related to hibernate save() and saveOrUpdate() methods.

Difference Between Save And Saveorupdate In Hibernate

Happy Learning !!