2011-04-20 40 views
1


在saveOrUpdate之前合併2個hibernate實體的最佳方式是什麼?
我從用戶(提交表單)獲得一個實體,我想用saveOrUpdate保存它。
如果用戶bean中不存在所有字段(用戶只能更新某些數據),則Hibernate將設置所有字段爲空。
這是我希望它看起來像:Java - 合併Hibernate bean /實體 - saveOrUpdate前

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

還要注意的是個人可以包含其他實體成員@OneToMany @ManyToMany和@ManyToOne

正如你已經瞭解,這種情況是隻更新。插入將是一個不同的故事。

感謝

回答

1

創建第三個目的在於saveOrUpdate似乎奇怪,當你已經有一個管理實體右出數據庫中有一起工作的。只需將允許用戶更改的字段複製到託管對象上並提交您的事務即可。除非你在getFromDB方法中對事務邊界做了一些奇怪的事情,否則沒有必要直接使用saveOrUpdate。

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的設置,那很好。雖然根據您提供的信息,但沒有看到任何理由讓它更復雜。

+0

我想跳過設置。組。組。並使其自動化......當使用大豆時,它更乾淨。 – fatnjazzy 2011-04-20 19:08:07

+0

嗯,我明白你現在要問什麼。它實際上是關於如何使魔術「合併」方法起作用的內部設計?如果你可以明確地定義它的需求,它可能會自己寫。你在用什麼框架?例如,Spring中的DataBinder會讓你想要發生的事情變得微不足道。 – Affe 2011-04-20 19:16:34

+0

這確實是一個完美的建議:DataBinder,一天後如果搜索!!!,謝謝 – fatnjazzy 2011-04-20 20:32:13