Difference Between Update And Saveorupdate In Hibernate

1. Overview

Difference Between Update And Saveorupdate In Hibernate Windows 7

In this tutorial, we'll discuss what cascading is in JPA/Hibernate. Then we'll cover the various cascade types that are available, along with their semantics.

The Session interface in Hibernate provides a couple of methods to move an object from a new or transient state to a persistent state e.g. Save, saveOrUpdate, and persist are used to store an object into the database, but there are some significant differences between them. The Session.save method does an INSERT to store the object into the database and it also returns.

Further reading:

Introduction to Spring Data JPA

In this video you will learn about Methods like Save-persist-saveOrUpdate Using a demo projectBelow is the GitHub link to download source:https://githu. Difference between session.save, session.saveOrUpdate and session.persist? Session.save: Save does an insert and will fail if the primary key is already persistent. Session.saveOrUpdate: saveOrUpdate does a select first to determine if it needs to do an insert or an update.Insert data if primary key not exist otherwise update data. Hibernate - difference between Session.save and Session.saveOrUpdate method The main difference between Session.save and Session.saveOrUpdate method is that save generates a new identifier and INSERT record into a database while Session.saveOrUpdate can either INSERT or UPDATE based upon existence of a record.

Introduction to Spring Data JPA with Spring 4 - the Spring config, the DAO, manual and generated queries and transaction management.

Mapping Entity Class Names to SQL Table Names with JPA

Learn how table names are generated by default and how to override that behavior.

2. What Is Cascading?

Entity relationships often depend on the existence of another entity, for example the PersonAddress relationship. Without the Person, the Address entity doesn't have any meaning of its own. When we delete the Person entity, our Address entity should also get deleted.

Cascading is the way to achieve this. When we perform some action on the target entity, the same action will be applied to the associated entity.

2.1. JPA Cascade Type

All JPA-specific cascade operations are represented by the javax.persistence.CascadeType enum containing entries:

  • ALL
  • PERSIST
  • MERGE
  • REMOVE
  • REFRESH
  • DETACH

2.2. Hibernate Cascade Type

Hibernate supports three additional Cascade Types along with those specified by JPA. These Hibernate-specific Cascade Types are available in org.hibernate.annotations.CascadeType:

  • REPLICATE
  • SAVE_UPDATE
  • LOCK

3. Difference Between the Cascade Types

3.1. CascadeType.ALL

CascadeType.ALLpropagates all operations — including Hibernate-specific ones — from a parent to a child entity.

Let's see it in an example:

Note that in OneToMany associations, we've mentioned cascade type in the annotation.

Now let's see the associated entity Address:

3.2. CascadeType.PERSIST

The persist operation makes a transient instance persistent. Cascade Type PERSIST propagates the persist operation from a parent to a child entity. When we save the person entity, the address entity will also get saved.

Let's see the test case for a persist operation:

When we run the above test case, we'll see the following SQL:

3.3. CascadeType.MERGE

The merge operation copies the state of the given object onto the persistent object with the same identifier. CascadeType.MERGE propagates the merge operation from a parent to a child entity.

Let's test the merge operation:

When we run the test case, the merge operation generates the following SQL:

Here, we can see that the merge operation first loads both address and person entities and then updates both as a result of CascadeType.MERGE.

3.4. CascadeType.REMOVE

As the name suggests, the remove operation removes the row corresponding to the entity from the database and also from the persistent context.

CascadeType.REMOVE propagates the remove operation from parent to child entity.Similar to JPA's CascadeType.REMOVE, we have CascadeType.DELETE, which is specific to Hibernate. There is no difference between the two.

Now it's time to test CascadeType.Remove:

When we run the test case, we'll see the following SQL:

The address associated with the person also got removed as a result of CascadeType.REMOVE.

3.5. CascadeType.DETACH

The detach operation removes the entity from the persistent context. When we use CascadeType.DETACH, the child entity will also get removed from the persistent context.

Let's see it in action:

Here, we can see that after detaching person, neither person nor address exists in the persistent context.

And

3.6. CascadeType.LOCK

Unintuitively, CascadeType.LOCK reattaches the entity and its associated child entity with the persistent context again.

Let's see the test case to understand CascadeType.LOCK:

Difference Between Save And Saveorupdate In Hibernate

As we can see, when using CascadeType.LOCK, we attached the entity person and its associated address back to the persistent context.

3.7. CascadeType.REFRESH

Refresh operations reread the value of a given instance from the database. In some cases, we may change an instance after persisting in the database, but later we need to undo those changes.

In that kind of scenario, this may be useful. When we use this operation with Cascade Type REFRESH, the child entity also gets reloaded from the database whenever the parent entity is refreshed.

For better understanding, let's see a test case for CascadeType.REFRESH:

Here, we made some changes in the saved entities person and address. When we refresh the person entity, the address also gets refreshed.

3.8. CascadeType.REPLICATE

The replicate operation is used when we have more than one data source and we want the data in sync. With CascadeType.REPLICATE, a sync operation also propagates to child entities whenever performed on the parent entity.

Now let's test CascadeType.REPLICATE:

Because of CascadeType.REPLICATE, when we replicate the person entity, its associated address also gets replicated with the identifier we set.

3.9. CascadeType.SAVE_UPDATE

CascadeType.SAVE_UPDATE propagates the same operation to the associated child entity. It's useful when we use Hibernate-specific operations like save, update and saveOrUpdate.

Let's see CascadeType.SAVE_UPDATE in action:

Because of CascadeType.SAVE_UPDATE, when we run the above test case, we can see that the person and address both got saved.

Here's the resulting SQL:

4. Conclusion

In this article, we discussed cascading and the different cascade type options available in JPA and Hibernate.

The source code for the article is available on GitHub.

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:>> CHECK OUT THE COURSE
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.

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.

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.

Difference Between Save And Saveorupdate In Hibernate With Example

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

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.

Diff Between Save And Saveorupdate In Hibernate

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.