Hi,
I have one general JPA (Hibernate) question regarding when one have the case with two classes and two relations between them. I supose that this will be interesting case for some people.
So, I have two classes with two relations between them, like this:
|Class1| <>-[1]--------[*]-> |Class2|
|Class1| ----------------[1]-> |Class2|
This is the actual code for these relations:
Class 1:
Code:
@javax.persistence.Entity
public class Class1 implements java.io.Serializable {
private Long id;
private java.util.Set<Class2> classes = new java.util.HashSet<Class2>();
private Class2 class2;
public Class1() {
}
@javax.persistence.Id
@javax.persistence.GeneratedValue
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@javax.persistence.OneToMany(mappedBy="class1", cascade=javax.persistence.CascadeType.ALL)
public java.util.Set<Class2> getClasses() {
return this.classes;
}
public void setClasses(java.util.Set<Class2> classes) {
this.classes= classes;
}
public Class2 getClass2() {
return this.class2;
}
public void setClass2(Class2 class2) {
this.class2 = class2;
}
}
Class 2:Code:
@javax.persistence.Entity
public class Class2 java.io.Serializable {
private Long id;
private Class1 class1;
public Class2() {
}
@javax.persistence.Id
@javax.persistence.GeneratedValue
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@javax.persistence.ManyToOne
public Class1 getClass1() {
return this.class1;
}
public void setClass1(Class1 class1) {
this.class1 = class1;
}
}
Now, the test code:
Code:
Class2 c1 = new Class2();
Class2 c2 = new Class2();
Class2 c3 = new Class2();
Set<Class2> list = new LinkedHashSet<Class2>();
list.add(c1); list.add(c2); list.add(c3);
Class1 in = new Class1();
in.setClasses(list); <- this is related to the first diagram
in.setClass2(c2); <- this is related to the second diagram
hib.persist(in); <- THIS DOESN'T WORK, because Hibernate first try to insert [b]in[/b] object (Class1), and it doesn't have id of the class2.
But if I write this changed test code:
Code:
Class2 c1 = new Class2();
Class2 c2 = new Class2();
Class2 c3 = new Class2();
Set<Class2> list = new LinkedHashSet<Class2>();
list.add(c1); list.add(c2); list.add(c3);
Class1 in = new Class1();
// Now I manually add ref to Class1 object
c1.setClass1(in);
c2.setClass1(in);
c3.setClass1(in);
in.setClasses(list); <- this is related to the first diagram
in.setClass2(c2); <- this is related to the second diagram
hib.persist(in); <- NOW IT WORKS!!! But why ?! It firstly writes Class1 objects, then Class2 objects and in the end it updates Class1 giving it reference to Class2.
The question is why this doesn't work in the first case when I don't manually add ref to Class1 object ?