2 Replies Latest reply on Nov 17, 2005 6:46 AM by epbernard

    About @OneToOne & @PrimaryKeyJoinColumn

    atodorov

      I want to define two tables that share the same primary key with bidirectional mapping. So I use the combination of @OneToOne and @PrimaryKeyJoinColumn:

      @Entity
      public class Person {
       //...
      
       @Id(generate = GeneratorType.TABLE)
       public Long getId() {
       return id;
       }
      
       @OneToOne(cascade = {CascadeType.ALL})
       @PrimaryKeyJoinColumn()
       public User getUser() {
       return user;
       }
      
       public void setUser(User user) {
       this.user = user;
       }
      
       //...
      }
      
      
      @Entity
      public class User {
       //...
      
       @Id(generate = GeneratorType.NONE)
       public Long getId() {
       return id;
       }
      
       @OneToOne(cascade = {CascadeType.ALL})
       @PrimaryKeyJoinColumn()
       public Person getPerson() {
       return person;
       }
      
       public void setPerson(Person person) {
       this.person = person;
       if (getId() == null) {
       setId(person.getId());
       }
       }
       //...
      }


      The problem is that if I try to create a new Person and a new User, and persist them simultaneously, an exception is thrown (explaining: "ids for this class must be manually assigned before calling save(): com.xxx.User").

      With the upper configuration, I can save the objects with this code:


      Person p = new Person();
      p.setXXX(...);
      User u = new User();
      u.setXXX(...);
      em.persist(p);
      u.setPerson(p);
      em.persist(u);
      //...
      


      But is it possible somehow to persist the objects simultaneously. I think it would be reasonable, because both of the entity objects KNOW that they share the same ID, so theoretically it should be possible to assign the new ID before persisting any of them...?