簡體   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