4 Replies Latest reply on Feb 15, 2006 2:58 PM by Denis Souza

    PrimaryKeyJoinColumn in OneToOne relationship

    Denis Souza Newbie

      Hi,

      I want to create a one-to-one bi-directional relationship in which both entities share the same primary key. So, following the example in the docs, I wrote this:

      @Entity
      public abstract class Customer {
      
       @Id
       @GeneratedValue(strategy = GenerationType.AUTO, generator = "C_SEQ")
       @SequenceGenerator(name = "C_SEQ", sequenceName = "CUSTOMER_SEQ")
       public Integer getId() {
       return id;
       }
      
       ...
      
       @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, optional = true)
       @PrimaryKeyJoinColumn
       public CustomerLogin getCustomerLogin() {
       return customerLogin;
       }
      }
      

      My other entity looks like this:
      @Entity
      public class CustomerLogin {
      
       @Id
       public Integer getId() {
       return id;
       }
      
       ...
      
       @OneToOne(optional = false, mappedBy = "customerLogin")
       public Customer getCustomer() {
       return customer;
       }
      


      Whenever I insert a customer/customerLogin pair I get the following exception:

      org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): CustomerLogin
      


      I was hoping that by using automatic ID generation in the customer entity and annotating the relationship with @PrimaryKeyJoinColumn it would automatically set the id in CustomerLogin. Note that the id is generated from a sequence in the database so if I want it to work like this I'd have to save the Customer entity, so that it would fetch the next id from the sequence, set the ID for CustomerLogin and then save CustomerLogin. Is there any way to make this automatic?