开发者

Java - Merge Hibernate beans/entities - before saveOrUpdate

What is the best way to merge 2 hibernate entities before saveOrUpdate.

I get one entity from the user(submitted form) and i want to save it using saveOrUpdate.

Hibernate will set all of the fields null if they are not existed in the user bean(the user can only update some of the data).

this is how i want it to look like:

//this is the data the submitted from the user form.
PersonEntity entityFromTheClient = getPersonEntityFromClient();

//this is the data that i pull from the d开发者_如何学编程b for the merge
PersonEntity entityFromDb = getPersonEntityFromDb(entityFromTheClient.getID()); //entityFromTheClient.getID() = PK

//this is the method that i need to merge entityFromTheClient into entityFromDb
PersonEntity dataMerged = (PersonEntity)SomeUtill.merge(entityFromTheClient,entityFromDb);

//this will save the merged data.
session.saveOrUpdate(dataMerged);

Also note that Person can contain other entities members @OneToMany @ManyToMany and @ManyToOne

As you already understand, this situation is for update only. insert will be a different story.

Thanks


Creating a third object to saveOrUpdate does seem strange when you already have a Managed Entity right out of the database there to work with. Just copy the fields that the user is allowed to change right onto the managed object and commit your transaction. There isn't really even any need to use saveOrUpdate explicitly unless you're doing something odd with the transaction boundaries in your getFromDB method.

Transaction tx = session.beginTransaction();

PersonEntity entityFromTheClient = getPersonEntityFromClient();

//this is the data that i pull from the db for the merge
PersonEntity entityFromDb = getPersonEntityFromDb(entityFromTheClient.getID()); 

entityFromDb.setA(entityFromTheClient.getA());
entityFromDb.setB(entityFromTheClient.getB());

tx.commit();

Actual transaction handling depends on your framework setup of course.

That's it, done. If you want to hide the setting inside some kind of Util that's fine. Don't see any reason to make it more complicated than that though based on the information you've provided.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜