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

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

    One other possible reason: in my case, I was attempting to save the child before saving the parent, on a brand new entity.

    The code was something like this in a User.java model:

    this.lastName = lastName;
    this.isAdmin = isAdmin;
    this.accountStatus = "Active";
    this.setNewPassword(password);
    this.timeJoin = new Date();
    create();
    

    The setNewPassword() method creates a PasswordHistory record and adds it to the history collection in User. Since the create() statement hadn't been executed yet for the parent, it was trying to save to a collection of an entity that hadn't yet been created. All I had to do to fix it was to move the setNewPassword() call after the call to create().

    this.lastName = lastName;
    this.isAdmin = isAdmin;
    this.accountStatus = "Active";
    this.timeJoin = new Date();
    create();
    this.setNewPassword(password);
    

提交回复
热议问题