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

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

    Case 1: I was getting this exception when I was trying to create a parent and saving that parent reference to its child and then some other DELETE/UPDATE query(JPQL). So I just flush() the newly created entity after creating parent and after creating child using same parent reference. It Worked for me.

    Case 2:

    Parent class

    public class Reference implements Serializable {
    
        @Id
        @Column(precision=20, scale=0)
        private BigInteger id;
    
        @Temporal(TemporalType.TIMESTAMP)
        private Date modifiedOn;
    
        @OneToOne(mappedBy="reference")
        private ReferenceAdditionalDetails refAddDetails;
        . 
        .
        .
    }
    

    Child Class:

    public class ReferenceAdditionalDetails implements Serializable{
    
        private static final long serialVersionUID = 1L;
    
        @Id
        @OneToOne
        @JoinColumn(name="reference",referencedColumnName="id")
        private Reference reference;
    
        private String preferedSector1;
        private String preferedSector2;
        .
        .
    
    }
    

    In the above case where parent(Reference) and child(ReferenceAdditionalDetails) having OneToOne relationship and when you try to create Reference entity and then its child(ReferenceAdditionalDetails), it will give you the same exception. So to avoid the exception you have to set null for child class and then create the parent.(Sample Code)

    .
    .
    reference.setRefAddDetails(null);
    reference = referenceDao.create(reference);
    entityManager.flush();
    .
    .
    

提交回复
热议问题