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

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

    i get this error when i use

    getSession().save(object)
    

    but it works with no problem when I use

    getSession().saveOrUpdate(object) 
    
    0 讨论(0)
  • 2020-11-22 07:30

    I faced this exception when I did not persist parent object but I was saving the child. To resolve the issue, with in the same session I persisted both the child and parent objects and used CascadeType.ALL on the parent.

    0 讨论(0)
  • 2020-11-22 07:32

    You should include cascade="all" (if using xml) or cascade=CascadeType.ALL (if using annotations) on your collection mapping.

    This happens because you have a collection in your entity, and that collection has one or more items which are not present in the database. By specifying the above options you tell hibernate to save them to the database when saving their parent.

    0 讨论(0)
  • 2020-11-22 07:33

    Or, if you want to use minimal "powers" (e.g. if you don't want a cascade delete) to achieve what you want, use

    import org.hibernate.annotations.Cascade;
    import org.hibernate.annotations.CascadeType;
    
    ...
    
    @Cascade({CascadeType.SAVE_UPDATE})
    private Set<Child> children;
    
    0 讨论(0)
  • 2020-11-22 07:33

    There is another possibility that can cause this error in hibernate. You may set an unsaved reference of your object A to an attached entity B and want to persist object C. Even in this case, you will get the aforementioned error.

    0 讨论(0)
  • 2020-11-22 07:34

    This isn't the only reason for the error. I encountered it just now for a typo error in my coding, which I believe, set a value of an entity which was already saved.

    X x2 = new X();
    x.setXid(memberid); // Error happened here - x was a previous global entity I created earlier
    Y.setX(x2);
    

    I spotted the error by finding exactly which variable caused the error (in this case String xid). I used a catch around the whole block of code that saved the entity and printed the traces.

    {
       code block that performed the operation
    } catch (Exception e) {
       e.printStackTrace(); // put a break-point here and inspect the 'e'
       return ERROR;
    }
    
    0 讨论(0)
提交回复
热议问题