I have 3 classes corresponding to 3 tables V
, D
and P
. D
had a FK to V
(FK_V
) and is join using OneToMany relationship. Also their exits a 4th table V_D_P
which has the relationship of these V
, D
and P
.
Following is what the data model for these looks like:
@Entity
@Table(name = "V")
public class V {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "ID")
private Long id;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name = "FK_V", referencedColumnName="Id", nullable = false)
private Set<D> d;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name = "FK_V", referencedColumnName="Id", nullable = false)
private Set<V_D_P> vdp;
//Getters Setters etc.
}
@Entity
@Table(name = "V_D_P")
public class V_D_P {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "ID")
private Long id;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "FK_D", nullable = false)
private D d;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "FK_P", nullable = false)
private P p;
//Getters Setters etc.
}
@Entity
@Table(name = "D")
public class D {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "ID")
private Long id;
//Getters Setters etc.
}
@Entity
@Table(name = "P")
public class P {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "ID")
private Long id;
//Getters Setters etc.
}
Now I want to persist V
, D
and P
along with their relationship. I am
V v = new V();
D d = new D();
Set<D> dSet = new HashSet<>();
dSet.add(d);
v.setD(dSet); // Adding d to V ....(1)
P p = new P();
V_D_P vdp = new V_D_P();
vdp.setD(d); // Adding d to V_D_P ....(2)
vdp.setP(p);
Set<V_D_P> vdpSet = new HashSet<V_D_P>();
vdpSet.add(vdp);
v.setVdp(vdpSet);
entityManager.persist(v);
Now you can see the I am adding the same d
object twice. Once to P and once to V_D_P. However since these are the same objects, only once of them should persist. However based on the hibernate logs I see that hibernate is trying to insert 2 different objects.
I also see the following exception: ORA-00001: unique constraint
Is there a way to let hibernate that these are the same objects and to persis them only once ?