0
  1. Comment class

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id")
    private User user;
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "image_id")
    private Image image;
    
  2. User class

    @OneToMany(mappedBy = "user", cascade = CascadeType.MERGE, fetch = 
    FetchType.EAGER)
    private List<Comment> comments = new ArrayList<>();
    
  3. Image class

    @OneToMany(mappedBy = "image",cascade = CascadeType.MERGE,fetch = 
    FetchType.EAGER)
    private List<Comment> comments = new ArrayList<Comment>();
    
  4. These are the ManyToOne and OneToMany relations I have. I am unable to persist the Comment object due to "detached entity passed to persist: ImageHoster.model.Comment" error.

Siva
  • 1
  • 1
  • 1
    Possible duplicate of [JPA/Hibernate: detached entity passed to persist](https://stackoverflow.com/questions/13370221/jpa-hibernate-detached-entity-passed-to-persist) – crizzis Jul 12 '19 at 19:11
  • I have tried the changes suggested in the previous post but no luck! – Siva Jul 12 '19 at 19:14

1 Answers1

0
  1. I kind of figured out the issue. In the CommentRepository class where I am persisting the Comment object, I used .merge instead of .persist

    EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); try{ transaction.begin(); em.merge(newComment);

  2. instead of em.persist(newComment);

Siva
  • 1
  • 1