一对多,一端设置:
<set name="TWorkorderHistories" inverse="true" cascade="all">
一)保存级联
问题:
一方主键数据库中没有,先保存多方时,回报引用暂时态对象错误,
分析:
先不关联多方地保存一方,
解决:
假设一方A,多方B
1)B.setA(A);
2)A.getSetB().add(B);
3)session.save(A);
或:
1 // 插入记录 2 session.saveOrUpdate(workorder); 3 tr.commit(); 4 session.close(); 5 6 session = hibernateDao.getHSession(); 7 tr = session.beginTransaction(); 8 // 添加工单历史 9 TWorkorderHistory tWorkorderHistory = new TWorkorderHistory(workorder, 10 pureUser, 1L, new Timestamp(new Date().getTime()), Short 11 .parseShort("0")); 12 13 session.saveOrUpdate(tWorkorderHistory); 14 workorder.getTWorkorderHistories().add(tWorkorderHistory); 15 16 // 插入记录 17 tr.commit(); 18 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
1 @Override 2 public void update(TWorkorderInfo workorder,User pureUser, String note, Short status) 3 throws DataAccessException { 4 5 6 7 workorder.setStatus(status); 8 workorder.setUpdated(new Timestamp(new Date().getTime())); 9 10 11 //开启事务 12 Session session = hibernateDao.getHSession(); 13 Transaction tr = session.beginTransaction(); 14 15 16 TWorkorderHistory tWorkorderHistory = new TWorkorderHistory(); 17 tWorkorderHistory.setTWorkorderInfo(workorder); 18 tWorkorderHistory.setCreated(new Timestamp(new Date().getTime())); 19 tWorkorderHistory.setOptType(status); 20 tWorkorderHistory.setNote(note); 21 tWorkorderHistory.setPureUser(pureUser); 22 tWorkorderHistory.setWorkflowId(1L); 23 24 session.saveOrUpdate(tWorkorderHistory); 25 workorder.getTWorkorderHistories().add(tWorkorderHistory); 26 27 28 session.merge(workorder); 29 tr.commit(); 30 session.close(); 31 }
问题二:
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
1 Session session = hibernateDao.getHSession(); 2 session.beginTransaction(); 3 TWorkorderInfo workorder = (TWorkorderInfo) session.load(clazz, workorderCode); 4 session.delete(workorder); 5 session.beginTransaction().commit();