javajpaejb-3.0

"detached entity passed to persist error" with JPA/EJB code


I am trying to run this basic JPA/EJB code:

public static void main(String[] args){
         UserBean user = new UserBean();
         user.setId(1);
         user.setUserName("name1");
         user.setPassword("passwd1");
         em.persist(user);
  }

I get this error:

javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.JPA.Database

Any ideas?

I search on the internet and the reason I found was:

This was caused by how you created the objects, i.e. If you set the ID property explicitly. Removing ID assignment fixed it.

But I didn't get it, what will I have to modify to get the code working?


Solution

  • ERD

    Let's say you have two entities Album and Photo. Album contains many photos, so it's a one to many relationship.

    Album class

    @Entity
    public class Album {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        Integer albumId;
    
        String albumName;
    
        @OneToMany(targetEntity=Photo.class,mappedBy="album",cascade={CascadeType.ALL},orphanRemoval=true)
        Set<Photo> photos = new HashSet<Photo>();
    }
    

    Photo class

    @Entity
    public class Photo{
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        Integer photo_id;
    
        String photoName;
    
        @ManyToOne(targetEntity=Album.class)
        @JoinColumn(name="album_id")
        Album album;
    
    }
    

    What you have to do before persist or merge is to set the Album reference in each photos.

            Album myAlbum = new Album();
            Photo photo1 = new Photo();
            Photo photo2 = new Photo();
    
            photo1.setAlbum(myAlbum);
            photo2.setAlbum(myAlbum);       
    

    That is how to attach the related entity before you persist or merge.