title: OneToOne between two tables with shared primary key
body: <p>I'm trying to set up the following tables using JPA/Hibernate:</p>
  
  <pre><code>User:
  
  userid - PK
  name 
  
  Validation:
  
  userid - PK, FK(user)
  code
  </code></pre>
  
  <p>There may be many users and every user may have max one validation code or none.</p>
  
  <p>Here's my classes:</p>
  
  <pre><code>public class User 
  {
      @Id
      @Column(name = "userid") 
      @GeneratedValue(strategy = GenerationType.IDENTITY)    
      protected Long userId;
  
      @Column(name = "name", length = 50, unique = true, nullable = false)
      protected String name;
  
      ...
  }
  
  public class Validation 
  {
      @Id
      @Column(name = "userid")
      protected Long userId;
  
      @OneToOne(cascade = CascadeType.ALL)
      @PrimaryKeyJoinColumn(name = "userid", referencedColumnName = "userid")
      protected User user;
  
      @Column(name = "code", length = 10, unique = true, nullable = false)
      protected String code;
  
      ...
  
      public void setUser(User user)
      {
          this.user = user;
          this.userId = user.getUserId();
      }
  
      ...
  }
  </code></pre>
  
  <p>I create a user and then try to add a validation code using the following code:</p>
  
  <pre><code>public void addValidationCode(Long userId)
  {   
      EntityManager em = createEntityManager();
      EntityTransaction tx = em.getTransaction();
  
      try 
      {
          tx.begin();
  
          // Fetch the user
          User user = retrieveUserByID(userId);
  
          Validation validation = new Validation();
          validation.setUser(user);
          em.persist(validation);
          tx.commit();
      }
      ...
  }
  </code></pre>
  
  <p>When I try to run it I get a org.hibernate.PersistentObjectException: detached entity passed to persist: User</p>
  
  <p>I have also tried to use the following code in my Validation class:</p>
  
  <pre><code>public void setUserId(Long userId)
  {
      this.userId = userId;
  }
  </code></pre>
  
  <p>and when I create a validation code I simply do:</p>
  
  <pre><code>Validation validation = new Validation();
  validation.setUserId(userId);
  em.persist(validation);
  tx.commit();
  </code></pre>
  
  <p>But then since User is null I get org.hibernate.PropertyValueException: not-null property references a null or transient value: User.code</p>
  
  <p>Would appreciate any help regarding how to best solve this issue!</p>