我有一個簡單的對象關係,我希望堅持使用hibernate。休眠,父母/小孩混淆
基本上,它的父母包含一個孩子的集合。我想要做的就是加載父項,否則創建它,向它添加元素並保存它。
這是在GWT環境中完成的,因此我將ChildDTO傳遞給此方法,該方法基本上只是Child類的非持久性版本(與gwts RPC序列化不兼容)。
public Integer testHibernate(Integer parentId, ChildDTO[] test) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Parent model;
if(parentId == null) {
// if the parentId is null, create new instance
model = new Parent);
}
else {
model = (Parent) hib.load(Parent.class, dto.getId());
}
model.setName("dummy name");
for(int i = 0; i < test.length) {
model.addChild(new Child(test[i].getId(), test[i].getName()));
}
hib.save(model);
hib.getTransaction().commit();
return model.getId();
}
對,這適用於創建新的父母,沒有孩子。如果我只是將一個孩子添加到現有父級,它也可以正常工作。但是,如果我添加了多個孩子,我從休眠狀態中收到「無法插入」錯誤。
此外,如果我嘗試添加一個孩子,已添加一個孩子的已有父母。我得到一個「具有相同標識符值的不同對象已經與會話相關聯」錯誤。
其他問題。當只插入一個孩子時,在一個空父母上,休眠會執行以下操作:
Hibernate: insert into Child(ChildId, ChildName) values (default, ?)
Hibernate: update Parent set ChildId=? where ChildId=?
更新內容如何? :S
請提供堆棧跟蹤。另外,顯示父/子關係的來源,顯示如何設置一對多關係。我的猜測是One-To-Many在數據庫或對象中設置不正確。 –
您可以顯示Parent和Child的hibernate映射嗎?同時顯示父類具體是什麼addChild做的。 –