title: Create a Tree using JPA
body: <p>I am trying to create a tree using entities and JPA. I have a class with the following properties. </p>
  
  <pre><code>public class Dir
  {
  
  @Id
  @Basic(optional = false)
  @NotNull
  @Column(name = "dirId")
  private Integer dirId;
  
  @OneToOne(mappedBy="dirId", cascade= CascadeType.ALL)
  private Dir parent;
  ...
  </code></pre>
  
  <p>A node knows who its parent is, and if it doesnt have a parent, it is the root. Thats how I can easily build a tree out of this. But...
  I dont think the mapping is correct for this thought. I get the following error when I try to deploy:</p>
  
  <pre><code>An incompatible mapping has been encountered between [class com.dv.oa.model.entity.dir.Dir] and [class com.dv.oa.model.entity.dir.Dir]. This usually occurs when the cardinality of a mapping does not correspond with the cardinality of its backpointer.
  </code></pre>
  
  <p>It talks about the cardinality. But this doesnt make sense, a node can only have one parent. This is why I chose <code>@OneToOne</code> </p>
  
  <p>Can anyone shed some light on this? I guess another way of asking this would be, how do you map an entity to another instance of itself?</p>
  
  <p>EDIT</p>
  
  <p>Here is my table structure:</p>
  
  <pre><code>mysql&gt; describe dir;
  +--------------+--------------+------+-----+---------+-------+
  | Field        | Type         | Null | Key | Default | Extra |
  +--------------+--------------+------+-----+---------+-------+
  | dirId        | int(11)      | NO   | PRI | NULL    |       |
  | DTYPE        | varchar(31)  | YES  |     | NULL    |       |
  | dirName      | varchar(255) | YES  |     | NULL    |       |
  | companyOwner | int(11)      | YES  | MUL | NULL    |       |
  | userOwner    | int(11)      | YES  | MUL | NULL    |       |
  | parent       | int(11)      | YES  |     | NULL    |       |
  +--------------+--------------+------+-----+---------+-------+
  6 rows in set (0.00 sec)
  </code></pre>