繁体   English   中英

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

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


在saveOrUpdate之前合并2个休眠实体的最佳方法是什么。
我从用户(提交的表单)获得一个实体,我想使用saveOrUpdate保存它。
如果用户Bean中不存在所有字段,则Hibernate会将所有字段设置为null(用户只能更新某些数据)。
这就是我想要的样子:

//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);

另请注意,Person可以包含其他实体成员@OneToMany @ManyToMany和@ManyToOne

如您所知,这种情况仅用于更新。 插入将是一个不同的故事。

谢谢

当您已经可以在数据库中使用托管实体时,创建第三个对象保存或更新似乎很奇怪。 只需将允许用户更改的字段直接复制到托管对象上并提交您的事务即可。 甚至根本不需要显式使用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();

当然,实际的事务处理取决于您的框架设置。

就这样,完成了。 如果您想将设置隐藏在某种Util中,那很好。 尽管根据您提供的信息,没有任何理由使它变得比这更复杂。

暂无
暂无

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

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