users@glassfish.java.net

RE: May an entity reference itself?

From: <w.rittmeyer_at_jsptutorial.org>
Date: Wed, 23 Apr 2008 13:45:09 +0200

It is possible to use a reference to objects of the same type. Say for example for a hierarchical list of topics:

@Entity
@Table(name="TOPIC")
@Inheritance(strategy=InheritanceType.JOINED)
public class Topic extends BaseObject implements Serializable {
   
   @OneToMany(mappedBy="parentTopic")
   @OrderBy(value="posInParentTopic")
   private List<Topic> topics;
   
   @ManyToOne
   @JoinColumn(name="TOPIC_ID")
   private Topic parentTopic;
   
   @Column(name="POS_IN_PARENT")
   private int posInParentTopic;

   //...
}

The last attribute is of course only relevant if the order of the elements in your list is important.
--
Wolfram Rittmeyer
Markus Karg wrote:
>I need to model an entity that points to iteself. The idea is to be able 
>to build a possibly endless chain of entities of the same type. In SQL 
>this is as simple as adding a foreign key to the same table. Is that 
>possible in JPA? May an entity have a relation to iteself? Or is there 
>another solution to this problem?
>
>Thanks
>Markus