There is table A , table B and table A_B , which is used for association. There are relevant entities:

 @Entity @Table(name = "A") public class A { @Id int id; @ManyToMany(cascade = ALL) @JoinTable( name = "A_B", joinColumns = {@JoinColumn(name = "a_id")}, inverseJoinColumns = {@JoinColumn(name = "b_id")} ) public List<B> list; } @Entity @Table(name = "B") public class B { @Id int id; } 

If you get several objects of type B from the database and add them to the list object A , and then save object A , then the following exception is thrown:

 Caused by: java.lang.IllegalStateException: Multiple representations of the same entity [com.example.B#342] are being merged. 

What is the reason and how to fix it?

Added an example

 B b1 = em.createQuery("SELECT b FROM B b WHERE some_condition", B.class).getSingleResult(; A a1 = new A(); a1.getList().add(b1); B b2 = em.createQuery("SELECT b FROM B b WHERE some_condition", B.class).getSingleResult(; A a2 = new A(); a2.getList().add(b2); em.merge(a1); em.merge(a2); 
  • code example is possible, where ejects knocks? And try cascade = {CascadeType.PERSIST, CascadeType.REFRESH} instead of cascade = ALL - JVic
  • Sample code added. If you specify without MERGE, the Primary Key (a_id, b_id) on the A_B table is violated. - Victor Khovanskiy

0