2

I have 3 table A ,B and mapping table A_B, which contains Id's of both (A_ID and B_ID). Following is how the java classes which map these 3 tables look like:

@Entity
@Table(name = "A")
public class A {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "ID")
    private Long id;

    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name = "FK_A", referencedColumnName="Id", nullable = false)
    private Set<A_B> ab;

    //Other attributes, Getters Setters etc.
}

@Entity
@Table(name = "A_B")
public class A_B {

     @Id
     @GeneratedValue(strategy = GenerationType.SEQUENCE)
     @Column(name = "ID")
     private Long id;

     @ManyToOne(cascade=CascadeType.ALL)
     @JoinColumn(name = "FK_B", nullable = false)
     private B b;

     //Other attributes, Getters Setters etc.
 }

Entity
@Table(name = "B")
public class B  {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "ID")
    private Long id;

    //Other attributes, Getters Setters etc.
}

Now lets say I have already persisted an object of B (b). Now I want to persist an Object of A (a) and the association between these two (ab). I have my code like :

@PersistenceContext(unitName = "demoPU")
private EntityManager em;

B b = em.createNamedQuery(queryName, B); // Getting obj of B
A a = new A();
A_B ab = new A_B();
ab.setB(b); // Setting B in relationship
a.setAb(ab);

em.persist(a);

However this tried to persist b again & since its id is already set, it throws en exception:

org.hibernate.PersistentObjectException: detached entity passed to persist

Can you let me know how can I persist the association in this case without having to persist B again ?

Suraj Menon
  • 1,486
  • 3
  • 28
  • 50

1 Answers1

0

Why don't you try to just set a and not b ?

You could also empty the set in a so it doesn't try to persist it.

EDIT: as said in comments it would not have the intended effect. You should use saveOrUpdate() instead of persist() as suggested in org.hibernate.PersistentObjectException: detached entity passed to persist

Community
  • 1
  • 1
Asoub
  • 2,273
  • 1
  • 20
  • 33