I. TreeNode
A node in the tree structure,
The primary key is ID, and the specific content is value.
Two-way connection between the two foreign keys, namely the parent node pid and the child node set children
[Java]
@ Entity
@ Table (name = "t_TreeNode ")
Public class TreeNode
{
Private int id;
Private String value;
Private TreeNode pid; // parent node id
Private Set <TreeNode> children = new HashSet <TreeNode> (); // subnode id
@ Id
@ GeneratedValue
Public int getId (){
Return id;
}
@ Onetoade (cascade = (CascadeType. ALL), mappedBy = "pid") // cascade ALL
Public Set <TreeNode> getChildren (){
Return children;
}
@ ManyToOne
@ JoinColumn (name = "p_Id") // specifies the foreign key name. The default value is group_Id.
Public TreeNode getPid (){
Return pid;
}
Ii. Storage
Set bidirectional Association
[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); // forward
Root. getChildren (). add (top2 );
Top1.getChildren (). add (sub1_1 );
Top1.getChildren (). add (sub1_2 );
Subcategory 1.setpid (top1); // reverse
Sub‑2.setpid (top1 );
Top1.setPid (root );
Top2.setPid (root );
Session. save (root); // because cascade is set, u1 and u2 are stored in the storage g.
Session. getTransaction (). commit ();
HibernateUtil. getSessionFactory (). close ();
}
3. Traversal
Recursive Traversal
[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 );
}
}