title: JPA: persisting entity with composite primary key
body: <p>I have two tables in database, A and B. Table B has an id composed of two fields. One of them is a foreign key to A. Id of A is automatically generated on insert by a sequence.</p>
  
  <pre><code>A:
      ID (PK)
      (*other fields*)
  
  B:
      SOME_FIELD (PK)
      A_ID (PK, FK to A)
  </code></pre>
  
  <p>I have mapped the two tables in JPA (Hibernate) following <a href="http://download.oracle.com/otn-pub/jcp/persistence-2.0-fr-eval-oth-JSpec/persistence-2_0-final-spec.pdf" rel="nofollow">JPA specification</a>, in this way:</p>
  
  <pre><code>@Entity
  @Table(name = "A")
  public class A implements Serializable {
      @Id
      @SequenceGenerator(name = "A_SEQ", sequenceName = "A_SEQ")
      @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "A_SEQ")
      @Column(name = "ID")
      private Long id;
    (...)
  }
  
  @Entity
  @Table(name = "B")
  public class B implements Serializable {
      @EmbeddedId
      @AttributeOverride(name = "someField", column = @Column(name = SOME_FIELD))
      private BPK pk;
  
      @MapsId("aId")
      @ManyToOne
      @JoinColumn(name = "A_ID")
      private A a;
    (...)
  }
  
  @Embeddable
  public class BPK implements Serializable {
      private Long aId;
      private String someField;
  
      @Override
      public boolean equals(Object o) {
          (...)
      }
  
      @Override
      public boolean hashCode() {
          (...)
      }
  
      (...)
  }
  </code></pre>
  
  <p>The problem is that when I try to save an B object calling entityManager.persist(b), where b.a is set to an A object, which exists already in database, I get an exception:</p>
  
  <pre><code>javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: package.name.A
  </code></pre>
  
  <p>I don't know why this happens. I'm trying to save object of class B, not A. Is my entity class wrong? Or maybe I shouldn't use persist here?</p>