Hibernate Updating an Existing Object with a New Object

Suppose I have a Foo entity in a DB.

I am parsing some files and creating new Foo objects and would like to check if the analyzed Foo object exists in the database (using a unique attribute). If it is already updated, it otherwise saves as a new object.

What is the best approach?

Can I just set the id and version to a new Foo object?

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

Thank.

+3
source share
3 answers

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

, Foo ( , , )

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

, Foo (newFoo)

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

saveOrUpdate(), merge(). , , . newFoo , , 1.

, Foo, . , . , , , , .

+2

, , , , . , , id "saveOrUpdate". - 10.7

0

, , , hql ?

like:

getHibernateTemplate().bulkUpdate("Update Foo set p1 = ?, ... where uniq_prop = ?", new Object[] {..., key});

If you first download the object, you will be given a choice to upgrade, which will double the queries you send to the database. The hql update option also has the advantage that you do not load a hibernate session with a multitude of objects (and when parsing a large file, the session size may become something you can control).

-1
source

Source: https://habr.com/ru/post/1738631/


All Articles