如何在具有多个表的休眠状态下呈现树结构? [英] How to render a tree structure in hibernate with multiple tables?
问题描述
我需要从其中定义了两个表的数据库中检索树:
I need to retrieve a tree from a DB in which I have two tables defined:
-
节点在这里,我定义了一个节点元素
node Here I define a node element
关系在这里,我通过指定使用ID的父母和孩子来定义树结构
relation Here I define the tree structure by specifying parents and children making use of IDs
在Internet上,我只找到带有单个表(即节点1)的表的示例,其中定义了节点和关系:
Looking on the Internet I only find examples with a single table, the node one, in which both nodes and relations are defined:
@Entity
@Table(name = "tree")
public class Node {
@Id
@GeneratedValue
private Integer id;
@NotNull
private String name;
@OneToMany
@JoinColumn(name = "parent_id")
@OrderColumn
private List<Node> children = new LinkedList<Node>();
}
即使它更简单,我也不喜欢它,因为基础表没有被规范化.
Even though it is simpler I don't like it very much because the underlying tables are not normalized.
任何人都可以使用两个表为我提供一个简单的示例吗?
Anyone can provide me with a simple example using two tables?
推荐答案
您可能希望在关系"表中有两列,
You may want to have two columns in Relationship table,
| id | parent_id |
|id | parent_id|
父节点条目将针对该节点的ID更新parent_id
Parent Node entry will update the parent_id against the id of the node
@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinTable(name="Relationship", joinColumns = @JoinTable(name = "Relationship", joinColumns = @JoinColumn(name = "parent_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "id", referencedColumnName = "id"))@Fetch(FetchMode.SELECT)
private Node parentNode;
类似地,子节点将根据ID的parent_id更新ID. 节点
Similarly child node will update the id against the parent_id of the node
@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@JoinTable(name = "Relationship", joinColumns = @JoinColumn(name = "id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "parent_id", referencedColumnName = "id"))
@Fetch(FetchMode.SELECT)
private Set<Node> childNodes;
这篇关于如何在具有多个表的休眠状态下呈现树结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!