Hibernate基础之:树状结构遍历
一:TreeNode
树结构的一个节点,
主键是ID,具体内容是value
双向连接俩外键,分别是父节点pid,和子节点的集合children
[java]
@Entity
@Table(name="t_TreeNode")
public class TreeNode
{
private int id;
private String value;
private TreeNode pid;//父节点id
private Set<TreeNode> children = new HashSet<TreeNode>(); //子节点id
@Id
@GeneratedValue
public int getId() {
return id;
}
@OneToMany(cascade=(CascadeType.ALL),mappedBy="pid")//级联用ALL
public Set<TreeNode> getChildren() {
return children;
}
@ManyToOne
@JoinColumn(name="p_Id")//指定外键名称,不指定的默认值是group_Id
public TreeNode getPid() {
return pid;
}
二:存储
设置双向的关联
[java]
@Test
public void testIN() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
TreeNode root = new TreeNode();
root.setValue("root");
TreeNode top1 = new TreeNode();
top1.setValue("top1");
TreeNode top2 = new TreeNode();
top2.setValue("top2");
TreeNode sub1_1 = new TreeNode();
sub1_1.setValue("sub1_1");
TreeNode sub1_2 = new TreeNode();
sub1_2.setValue("sub1_2");
root.getChildren().add(top1);//正向
root.getChildren().add(top2);
top1.getChildren().add(sub1_1);
top1.getChildren().add(sub1_2);
sub1_1.setPid(top1);//反向
sub1_2.setPid(top1);
top1.setPid(root);
top2.setPid(root);
session.save(root);//因为设置级联,所以存储g时候也把u1和u2存上了。
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
}
三:遍历
递归遍历
[java]
@Test
public void testOut() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
TreeNode node = (TreeNode)session.get(TreeNode.class, 1);
print(node);
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
}
public void print(TreeNode n)
{
System.out.println(n.getValue());
for(TreeNode child : n.getChildren())
{
print(child);
}
}
补充:软件开发 , Java ,