简体   繁体   English

Java-合并Hibernate bean /实体-在saveOrUpdate之前

[英]Java - Merge Hibernate beans/entities - before saveOrUpdate


What is the best way to merge 2 hibernate entities before saveOrUpdate. 在saveOrUpdate之前合并2个休眠实体的最佳方法是什么。
I get one entity from the user(submitted form) and i want to save it using saveOrUpdate. 我从用户(提交的表单)获得一个实体,我想使用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). 如果用户Bean中不存在所有字段,则Hibernate会将所有字段设置为null(用户只能更新某些数据)。
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 另请注意,Person可以包含其他实体成员@OneToMany @ManyToMany和@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. 甚至根本不需要显式使用saveOrUpdate,除非您对getFromDB方法中的事务边界做了一些奇怪的事情。

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. 如果您想将设置隐藏在某种Util中,那很好。 Don't see any reason to make it more complicated than that though based on the information you've provided. 尽管根据您提供的信息,没有任何理由使它变得比这更复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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