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

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

    This issue happened to me when I created a new entity and an associated entity in a method marked as @Transactional, then performed a query before saving. Ex

    @Transactional
    public someService() {
        Entity someEntity = new Entity();
        AssocaiatedEntity associatedEntity = new AssocaitedEntity();
        someEntity.setAssociatedEntity(associatedEntity);
        associatedEntity.setEntity(someEntity);
    
        // Performing any query was causing hibernate to attempt to persist the new entity. It would then throw an exception
        someDao.getSomething();
    
        entityDao.create(someEntity);
    }
    

    To fix, I performed the query before creating the new entity.

提交回复
热议问题