Problem with bidirectional OneToMany relationship [message #630442] |
Sat, 02 October 2010 15:13 |
dcarbonne Messages: 14 Registered: October 2010 |
Junior Member |
|
|
Hi,
I'm new to EclipseLink and JPA and have a problem understanding what is wrong with my code. I hope this is the right forum for my question.
I tried to find if it was already asked on the net, but did not succeed.
I want to model a bidirectional OneToMany relationship between two classes A and B:
A (0..1) <--> (0..n)B.
If I annotate A.b with @OneToMany(mappedBy="a"), then the A->B relation table is not generated.
When I move this annotation to the getter (A.getB()), then the relation table is generated.
I should say that if I remove (mappedBy="a"), then there are two mono-directional relationships, and things work as expected.
I'm quite surprised by this behaviour. IIUC JPA specification, annotations must only be used on FIELDS or (exclusive) PROPERTIES. To make things work (as I would like them to), there is a mix of annotations, which seems wrong to me.
I don't understand why initial code does not work, and why modified one works!
What am I doing wrong?
This example seems so close to examples I've read that is is quite frustrating.
The behaviour is he same on Windows and Linux (I use latest Helios, derby and EclipseLink on both systems).
Thanks in advance for your help.
Regards,
Damien Carbonne
Code follows.
tests02/A.java
package test02;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
@Entity
public class A implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private int id;
@OneToMany(mappedBy = "a") // YThis does not work as expected
private List<B> b = new ArrayList<B>();
public A() {
super();
}
public A(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public void setB(List<B> b) {
this.b = b;
}
// When using this annotation (and commenting the above one), things work as expected (by me)
// @OneToMany(mappedBy = "a")
public List<B> getB() {
return b;
}
}
tests02/B.java
package test02;
import java.io.Serializable;
import javax.persistence.*;
@Entity
public class B implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private int id;
@ManyToOne
private A a;
public B() {
super();
}
public B(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
}
|
|
|
|
|
Powered by
FUDForum. Page generated in 0.03329 seconds