object references an unsaved transient instance - save the transient instance before flushing

错误提示后面还有一些提示,提示是哪个对象出现问题!

原因可能是:我们没有给这个对象赋值,此时 Hibernate 会 new 一个 空对象 保存给这个对象,空对象在数据库肯定是没有的,即提示所说的unsaved
transient instance(未保存状态的临时实例 或者说 游离态)提示我们要先保存! 所以在保存该对象的时候就会错误。
解决的办法是:
1. 判断对象是否为空,空的话,直接设置这个对象为空(null)或者给个默认值,而不是给它个空对象!

例如:

//如果不填部门则默认为该员工所在的部门
            if (task.getDept()==null || task.getDept().getId()==null) {
                //task.setDept(null);
                Employee employee = empService.get(task.getEmp().getId());
                task.setDept(employee.getDept());
            }

如果您还有其他解决办法,或者觉得我所言有错误,欢迎留言。

猜你喜欢

转载自blog.csdn.net/MOESECSDN/article/details/79947860