简体   繁体   中英

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 db 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM