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

前端 未结 30 1057
既然无缘
既然无缘 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:17

    Don't use Cascade.All until you really have to. Role and Permission have bidirectional manyToMany relation. Then the following code would work fine

        Permission p = new Permission();
        p.setName("help");
        Permission p2 = new Permission();
        p2.setName("self_info");
        p = (Permission)crudRepository.save(p); // returned p has id filled in.
        p2 = (Permission)crudRepository.save(p2); // so does p2.
        Role role = new Role();
        role.setAvailable(true);
        role.setDescription("a test role");
        role.setRole("admin");
        List pList = new ArrayList();
        pList.add(p);
        pList.add(p2);
        role.setPermissions(pList);
        crudRepository.save(role);
    

    while if the object is just a "new" one, then it would throw the same error.

提交回复
热议问题