Java - Merge Hibernate beans/entities - before saveOrUpdate
//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.
精彩评论