How to fix the Hibernate “object references an unsaved transient instance - save the transient instance before flushing” error

前端 未结 30 1569
既然无缘
既然无缘 2020-11-22 07:11

I receive following error when I save the object using Hibernate

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


        
30条回答
  •  滥情空心
    2020-11-22 07:43

    To add my 2 cents, I got this same issue when I m accidentally sending null as the ID. Below code depicts my scenario (and OP didn't mention any specific scenario).

    Employee emp = new Employee();
    emp.setDept(new Dept(deptId)); // --> when deptId PKID is null, same error will be thrown
    // calls to other setters...
    em.persist(emp);
    

    Here I m setting the existing department id to a new employee instance without actually getting the department entity first, as I don't want to another select query to fire.

    In some scenarios, deptId PKID is coming as null from calling method and I m getting the same error.

    So, watch for null values for PK ID

提交回复
热议问题