use*_*041 2 java database tree jpa
我正在尝试使用实体和 JPA 创建一棵树。我有一个具有以下属性的类。
public class Dir
{
@Id
@Basic(optional = false)
@NotNull
@Column(name = "dirId")
private Integer dirId;
@OneToOne(mappedBy="dirId", cascade= CascadeType.ALL)
private Dir parent;
...
Run Code Online (Sandbox Code Playgroud)
一个节点知道它的父节点是谁,如果它没有父节点,那么它就是根。这就是我如何轻松地用它构建一棵树的方法。但是......我认为这个想法的映射是不正确的。当我尝试部署时出现以下错误:
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.
Run Code Online (Sandbox Code Playgroud)
它谈论基数。但这没有意义,一个节点只能有一个父节点。这就是我选择的原因@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)
Run Code Online (Sandbox Code Playgroud)
您指向映射所属方的错误列。此外,你们的关系不是一对一的,因为单亲可以有很多孩子。
@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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13541 次 |
最近记录: |