title: Java/Hibernate/JPA: cannot persist with compound key -> transient object
body: <p>my problem is that I cannot save my entity because it contains another entity, mapped by a key that is also a part of this table's primary key. The table looks like this:</p>
  
  <pre><code>table C:
  
  +-----+------+
  | id_A | id_B |
  +-----+------+
  </code></pre>
  
  <p>..where idA is the primary key of table A with <code>EntityA</code> and idB the primary key of table B with <code>EntityB</code>.</p>
  
  <p>so its basically a n-to-m relation. This is the entity I'm using for table C:</p>
  
  <pre><code>@Entity
  public class EntityC {
  
      private long idA;
      private EntityB b;
  
      @Id
      @Column(name = "id_A")
      public long getIdA() {
          return idA;
      }
  
      @Id
      @OneToOne(cascade = CascadeType.ALL)
      @JoinColumn(name = "id_B")
      public EntityB getB() {
          return b;
      }
  
      ...setters are here...
  
  }
  </code></pre>
  
  <p>Please note that <code>id_A</code> is mapped as is (the id), while <code>id_B</code> is mapped as its object representation, <code>EntityB</code>. This is what I want to do with it:</p>
  
  <pre><code>EntityC c = new EntityC();
  c.setIdA(123);
  c.setB(new EntityB());
  
  em.persist(c);
  tx.commit();
  em.close();
  </code></pre>
  
  <p>I want to persist <code>EntityB</code> ONLY IF I can persist <code>EntityC</code>.</p>
  
  <p>on <code>tx.commit()</code> I get this exception: <code>org.hibernate.TransientObjectException: object references an unsaved transient instance</code></p>
  
  <p>I suppose this happens because part of the primary key, <code>id_B</code>, is not saved. But i set cascading to all so there should be no problem!</p>
  
  <p>Why is this not working?</p>
  
  <hr>
  
  <p>EDIT:</p>
  
  <p>When I do this:</p>
  
  <pre><code>em.persist(c.getB());
  em.persist(c);
  </code></pre>
  
  <p>it works. But can't Hibernate/JPA do that automatically? I thought that's what cascading is good for.</p>
  
  <hr>
  
  <p>EDIT2:</p>
  
  <p>added an embeddedId instead of id_A and id_B:</p>
  
  <pre><code>@Embeddable
  public class EntityCID implements Serializable {
  
  public long idA;
  
  @OneToOne(cascade = CascadeType.ALL)
  @JoinColumn(name = "id_B", referencedColumnName = "id")
  public EntryB b;
  
  }
  </code></pre>
  
  <p>EntityC now looks like:</p>
  
  <pre><code>@Entity
  public class EntityC implements Serializable {
  
      private EntityCID id;
      ...
  
      @EmbeddedId
      public void getId() {
          return id;
      }
  
  }
  </code></pre>
  
  <p>but I still get the transient object exception if I don't <code>em.persist(c.getId().b);</code> before <code>em.persist(c)</code>. Sticking to that, although it is ugly.</p>
  
  <p>@Trein: it is not bidirectional. EntityB code:</p>
  
  <pre><code>@Entity
  public class EntityB implements Serializable {
      public long id;
      public String text;
  }
  </code></pre>