Skip to main content

Instantiate Entity that has foreign key attribute

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
No replies
Pacopag
Offline
Joined: 2014-03-21

Suppose we have two entities related like this

<br />
@Entity<br />
public class ParentEntity implements Serializable {<br />
   @Id<br />
   private int id;<br />
}<br />

and
<br />
@Entity<br />
public class ChildEntity implements Serializable {<br />
   @Id<br />
   private int id;<br />
   @ManyToOne<br />
   @JoinColumn('parent')<br />
   private ParentEntity parent;</p>
<p>   public ChildEntity(){<br />
   }<br />
   public ChildEntity(ParentEntity parent) {<br />
      this.parent = parent;<br />
   }<br />
}<br />

I'm wondering how we can create an instance of ChildEntity without already having a reference to the related ParentEntity. For example, let's say I already have the ParentEntity's id, but not the whole object. I tried doing something like
ChildEntity.class

<br />
   @PersistenceContext(unitName="myPersistenceUnit")<br />
   private EntityManager em;</p>
<p>   public ChildEntity(int parentId) {<br />
      ParentEntity parent = em.find(ParentEntity.class,parentId);<br />
      this.parent = parent;<br />
   }<br />

as I can afford the extra db hit. But the app fails to deploy because the container seems to think that ChildEntity no longer has an @Id declaration. Simply injecting the PersistenceContext causes this failure, let alone using the EntityManager.

So again, how does one go about instantiating an Entity that has a foreign key using only the foreign key object's id?