开发者

Hibernate Updating an existing entity with a new object

Assume I have an entity Foo in the DB.

I am parsing some files and creating new Foo objects and w开发者_开发百科ould 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.


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.


If you're not sure that the entity is in the database, then it's probably a detached entity. You can have hibernate choose whether to save or update the entity by setting the id and all other fields, and calling "saveOrUpdate". It's all there in the documentation - section 10.7


If you don't have the id in the file you're parsing, is your object so complex that using hql to update it is not an option ?

like :

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

If you load the entity first, you will issue a select by update, that will double requests you will send to the database. The hql update option has also the advantage of not loading your hibernate session with many objects (and when parsing a big file, the session size may become something to monitor).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜