Monday, May 11, 2015

JPA exception: org.hibernate.PersistentObjectException: detached entity passed to persist

When I saved a collection of form data into database by using JPA, I got "detached entity passed to persist" error.

I have a CompanyClass entity, and inside CompanyClass entity, I have a one to one relationship to Filestore entity.  See detail relationship of these two entities at JPA relationship between entities.

The save method I wrote in my service impl is like following:

     @PersistenceContext   
     private EntityManager emgr; 
     @Override  
     @Transactional  
      public void saveClass(CompanyClass cclass)  
                throws Exception {  
           emgr.persist(cclass);  
           emgr.close();  
      }  


But when I ran it, I got exception: org.hibernate.PersistentObjectException: detached entity passed to persist.

After research, I found out I shouldn't use

 emgr.persist(cclass);  

Instead, I should use

  emgr.merge(cclass);  


I found a blog about JPA: persisting vs. merging entites . It is clear about when we should use persist, and when we should use merge.

In my case, it falls into this:

You want to insert a new entity that may have a reference to another entity that may but may not be created yet (relationship must be marked MERGE). For example, inserting a new photo with a reference to either a new or a preexisting album.


No comments:

Post a Comment