1 Reply Latest reply on Nov 8, 2006 11:54 AM by Alex Grönholm

    mapping 0..1 association

    Arvind J Newbie

      Hi,

      I was wondering what is the best approach to map an association of the kind where one side is 0..1 and the other is 0..*

      I tried using OneToMany annotation along with nullable set to true, but that doesn't work.

      Do I have to do this using ManyToMany and provide code to check and enforce that one side does not have more than 1 instance?

      Thanks

        • 1. Re: mapping 0..1 association
          Alex Grönholm Novice

           

          I tried using OneToMany annotation along with nullable set to true, but that doesn't work.

          Associations are "optional" by default.
          To enforce 1..* or 1..1 associations, you'd have to do:
          @ManyToOne(optional = false)

          What exactly isn't working? Are you using the "mappedBy" property correctly?

          Example:
          @Entity
          public class A {
          ...
          @OneToMany(mappedBy = "myA")
          public List<B> getBList() {
           return bList;
          }
          ...
          }
          
          @Entity
          public class B {
          ...
          @ManyToOne
          public A getMyA() {
           return myA;
          }
          ...
          }