一对多,一端设置:
<set name="TWorkorderHistories" inverse="true" cascade="all">
一)保存级联
问题:
一方主键数据库中没有,先保存多方时,回报引用暂时态对象错误,
分析:
先不关联多方地保存一方,
解决:
假设一方A,多方B
1)B.setA(A);
2)A.getSetB().add(B);
3)session.save(A);
或:
// 插入记录
session.saveOrUpdate(workorder);
tr.commit();
session.close(); session = hibernateDao.getHSession();
tr = session.beginTransaction();
// 添加工单历史
TWorkorderHistory tWorkorderHistory = new TWorkorderHistory(workorder,
pureUser, 1L, new Timestamp(new Date().getTime()), Short
.parseShort("0")); session.saveOrUpdate(tWorkorderHistory);
workorder.getTWorkorderHistories().add(tWorkorderHistory); // 插入记录
tr.commit();
session.close();
保存级联
二)修改级联
问题一:
org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessions
解决:
参考:http://blog.163.com/chinagujing@yeah/blog/static/170937439201092405558777/
http://littie1987.iteye.com/blog/1039082
@Override
public void update(TWorkorderInfo workorder,User pureUser, String note, Short status)
throws DataAccessException { workorder.setStatus(status);
workorder.setUpdated(new Timestamp(new Date().getTime())); //开启事务
Session session = hibernateDao.getHSession();
Transaction tr = session.beginTransaction(); TWorkorderHistory tWorkorderHistory = new TWorkorderHistory();
tWorkorderHistory.setTWorkorderInfo(workorder);
tWorkorderHistory.setCreated(new Timestamp(new Date().getTime()));
tWorkorderHistory.setOptType(status);
tWorkorderHistory.setNote(note);
tWorkorderHistory.setPureUser(pureUser);
tWorkorderHistory.setWorkflowId(1L); session.saveOrUpdate(tWorkorderHistory);
workorder.getTWorkorderHistories().add(tWorkorderHistory); session.merge(workorder);
tr.commit();
session.close();
}
更新级联
问题二:
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.bonc.pure.domain.User
分析:
前台忘记传这个User了,一共有两个这样的User对象,后台只set了一个,前台传的是workorder.pureUserByModifier.userName,
struts给new的这个User对象只有userName一个属性,没有userId,而主键关联是需要通过userId的
解决:
<s:hidden name="workorder.pureUserByModifier.userId"></s:hidden>
二) 删除级联
问题:
org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessions
解决:
参考:http://www.itzhai.com/hibernate-one-to-many-association-mapping-configuration-and-the-cascade-delete-problem.html
Session session = hibernateDao.getHSession();
session.beginTransaction();
TWorkorderInfo workorder = (TWorkorderInfo) session.load(clazz, workorderCode);
session.delete(workorder);
session.beginTransaction().commit();
删除级联