2 Replies Latest reply on Dec 30, 2005 7:33 PM by epbernard

    Question about OneToOne relationships where other table's PK

    dbudworth

      I have two tables
      User (pkcol user_id(Long))
      UserDetail (pkcol user_id(Long), also foreign key to User)

      I read in the Hibernate Annotation Reference section 2.2.5.1 (OneToOne)
      section a piece saying that the slave table should have the id itself mapped as the raw value (ie: mapped as Long, rather than User object).

      It states that the application logic must manually set the Id on the slave for now. That it would be implemented in the future to automatically set it.

      I was wondering if the documentation is up to date. I've been trying to see if I can do this style of mapping without adding an unused UserDetailId column and sequence (I'm using oracle) for all my tables that are 1-1 mapped like this.

      Ultimately, Id prefer to have something like:


      (semi-pseudo code here)

      class User{
       @Id
       @Column(name="Id")
       Long userId;
      
       @OneToOne
       UserDetail detail;
      }
      
      class UserDetail{
       @OneToOne
       @Id
       @Column("user_id")
       User user;
      }
      


      Obviously simplified, but you get the jist (I hope).

      Will this be possible in the (near) future?

      In the mean time, I'll add extra id cols to my tables to get it working code wise (totally new development, doesnt hurt to make the tables a bit bigger)

        • 1. Re: Question about OneToOne relationships where other table'
          ycswyw

          If you don't want the unused "UserDetail" column and sequence , you can try with this code (not tested)

          class User{
          @Id
          @Column(name="user_id")
          Long userId;

          @OneToOne(optional = true)
          @JoinColumn(name="user_id")
          UserDetail detail;
          }

          class UserDetail{
          @Id(generate = GeneratorType.NONE)
          @Column("user_id")
          Long userId;

          @OneToOne()
          @JoinColumn(name = "user_id")
          User user;
          }



          But you must also have to set the Id on the slave:
          i.e:

          @PersistenceContext
          private EntityManager manager;

          public void test() {
          user = new User();
          manager.persist(user);
          UserDetail detail = new UserDetail();
          detail.userId = user.userId;
          detail.user = user;
          manager.persist(detail);
          }

          • 2. Re: Question about OneToOne relationships where other table'
            epbernard

            this is doable I think using the @GenericGenerator and the foreign strategy