Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Updating an existing entity with a new object

Tags:

hibernate

Assume I have an entity Foo in the DB.

I am parsing some files and creating new Foo objects and would like to check if the parsed Foo object exists in the DB (using a unique attribute). If it exists already update it otherwise save as a new object.

What is the best approach?

Could I simply set the id and version in the new Foo object?

Or would I be better off loading the Foo object from the DB and copying over the properties from the parsed file?

Thanks.

like image 209
DD. Avatar asked Mar 26 '10 09:03

DD.


People also ask

Which method of the session interface is used to update an already existing record in the database table?

Hibernate merge can be used to update existing values, however this method create a copy from the passed entity object and return it.

What is the difference between Merge and update method in 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.

How do you update an object in hibernate?

We can update an object in hibernate by calling the update() method, provided by the org. hibernate. Session. Though the update() method is used to update an object, there are two different ways to use update() method.

What is session merge () method in hibernate?

session. The merge() method is used when we want to change a detached entity into the persistent state again, and it will automatically update the database. The main aim of the merge() method is to update the changes in the database made by the persistent object.


1 Answers

Let's say that Foo has some properties of size, color, and alignment.

So the Foo in the database has these properties (and you have already determined that this is the correct one using your uniqueness attribute)

id=1, size=12, color=null, alignment="c"

Then let's say that the new Foo (newFoo) object has the following properties

id=(none yet), size=14, color="red", alignment=null

The options you have are to either use the saveOrUpdate() method or the merge() method. Both will result in the new object being saved over the old object but maintaining the old object's id. The new object stored will have the properties of newFoo above but with the id set to 1.

However, if you want to only override certain properties of Foo, you might have to load the object from the database and copy them over manually. For example, in this case, alignment is overwritten with null. If you wanted alignment to only be overwritten in cases where the new value is not null, then I think you need to copy the values over manually.

like image 151
Rachel Avatar answered Oct 04 '22 00:10

Rachel