3 Replies Latest reply on Jan 18, 2008 2:37 AM by linux enthusiast

    OneToMany Behaviour

    linux enthusiast Newbie

      I have a requirement to model a ManyToMany with additional attributes in the intersection table and based on all my reaearch, it looks like modelling this as a 2 OneToMany relationships is the right approach.

      1. Create three clases Class A, ClassB and ClassAB (Intersection)
      2. Define OneToMany from A -> AB
      3. Define OneToMany from B -> AB

      I wanted to clarify few observation that I have, before going ahead and completeing the implementation.

      Class A:

      @Table(name = "A")
      public class A {
       private List<AB> ab;
       public void setAb(List<AB> ab) {
       this.ab = ab;

      Class AB:

      @Table(name = "AB")
      public class AB {
       Do we need to specify an @Id column? It looks like
       the code works only if I define a seperate @id column as
       shown below. Also tried defining @Id as column "A_ID" with no
       success. Did I miss something?
       private int id;
       public void setId() {
       return id;
       @JoinColumn(name = "A_ID", nullable=false)
       private A a;
       public void setA(A a) {
       this.a = a;

      Test Case:

      public class ATest {
       public void createAWithAB() {
       List<AB> abList = new ArrayList<AB>();
       //Create A using appropriate constructor
       A a = new A("....");
       //Create a new Party Address and set the Location.
       AB ab = new AB();
       ab.setA(a); //Set A on the intersection AB
       // Creates an Person
       Should the AB record get created when we make the
       following call
       em.persist(a); //Persists A
       Do we need to make a explicity call to persist AB?
       It looks like that the AB record only gets sved if we
       make this following Persist call
       em.persist(ab); //Persisit AB

      Please let me know whether my obsevations are correct. Otherwise can you please provide some guidance on how to fix these issues. If correct, then what is the relevance of the @OneToMnay annotation in the "Class A" and the setter "setAB()"?