我正在尝试使用Entities和JPA创建一个树。我有一个具有以下属性的类。
public class Dir
{
@Id
@Basic(optional = false)
@NotNull
@Column(name = "dirId")
private Integer dirId;
@OneToOne(mappedBy="dirId", cascade= CascadeType.ALL)
private Dir parent;
...
一个节点知道它的父节点是谁,如果它没有父节点,它就是根节点。所以我可以很容易地用它建一棵树。但是…
我认为映射不适合这种想法。尝试部署时出现以下错误:
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.
它谈到基数。但这没有意义,一个节点只能有一个父节点。这就是为什么我选择
@OneToOne
有人能解释一下吗?我想问这个问题的另一种方式是,如何将一个实体映射到它自己的另一个实例?
编辑
这是我的表格结构:
mysql> 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)
最佳答案
您指向的映射所属方的列不正确。你的关系也不是一个单一的,因为单亲可以有很多孩子。
@Entity
public class Dir
{
//This field is a table column
//It uniquely identifies a row on the DIR table
@Id
private int dirId;
//This field is a table column
// It identifies the parent of the current row
// It it will be written as the type of dirId
// By default this relationship will be eagerly fetched
// , which you may or may not want
@ManyToOne(fetch=FetchType.LAZY, cascade={CascadeType.PERSIST, CascadeType.MERGE})
private Dir parent;
//This field is not a table column
// It is a collection of those Dir rows that have this row as a parent.
// This is the other side of the relationship defined by the parent field.
@OneToMany(mappedBy="parent")
private Set<Dir> children;
}
关于java - 使用JPA创建树,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14388037/