Exception in thread "main" org.hibernate.TransientObjectException: object references an unsaved tran

xiaoxiao2021-02-28  80

今天在使用一对多,多对一保存数据的时候出现了这个错误

Hibernate错误:

Exception in thread "main" org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: zhongfucheng.domain.Employee

为啥出现这个错误呢???在保存对象的时候,发现这个对象还有存在外键,这个外键是在另一个实体里面。这个实体如果不存在或者实体的主键为空,就会报这个错误!

而我在保存的时候,并没有把拥有外键的对象保存进去….只保存了“一”方面的对象。

//创建对象 Dept dept = new Dept(); dept.setDeptName("开发部"); Employee zs = new Employee(); zs.setEmpName("张珊"); zs.setSalary(1111); Employee ls = new Employee(); ls.setEmpName("李四"); ls.setSalary(2222); //添加关系 dept.getSet().add(zs); dept.getSet().add(ls); session.save(dept); /*当时我没有把Emploey对象保存一起保存...因此出现了这个错误 session.save(zs); session.save(ls);*/

还有一个解决方案:在映射文件中配置级联保存更新

转载请注明原文地址: https://www.6miu.com/read-61887.html

最新回复(0)