Hibernate學習筆記(六) --- 使用Hibernate建立一個樹

樹也是一種一對多的關係,同普通一對多關係的區別在於他的「一」的一方及「多」的一方均是同一類對象,所以能夠用一對多來實現樹,惟一的區別是將映射的對象類型設置爲自身便可java

以Person對象爲例,人類有父親及孩子,其中父親只有一個,孩子有多個,父親是Person對象,孩子是Person對象的集合mysql

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 import javax.persistence.CascadeType;
 5 import javax.persistence.Column;
 6 import javax.persistence.Entity;
 7 import javax.persistence.FetchType;
 8 import javax.persistence.Id;
 9 import javax.persistence.JoinColumn;
10 import javax.persistence.ManyToOne;
11 import javax.persistence.OneToMany;
12 
13 @Entity(name = "Person")
14 public class Person {
15     @Id
16     @Column(name = "NAME", length = 50)
17     private String name;
18 
19     @ManyToOne
20     @JoinColumn(name = "PARENTID")
21     private Person parent;
22 
23     @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
24     private List<Person> children = new ArrayList<Person>();
25 
26     public Person() {
27     }
28 
29     public Person(String name) {
30         this.name = name;
31     }
32 
33     public List<Person> getChildren() {
34         return children;
35     }
36 
37     public void addChild(Person person) {
38         children.add(person);
39         person.setParent(this);
40     }
41 
42     public void removeChild(Person person) {
43         children.remove(person);
44         person.setParent(null);
45     }
46 
47     public Person getParent() {
48         return parent;
49     }
50 
51     public void setParent(Person parent) {
52         this.parent = parent;
53     }
54 }

構建測試用例以下:sql

import study.hibernate.SessionManager;

public class Launcher {
    public static void main(String[] args) {
        Person person = new Person("張三");
        SessionManager.add(person);
        Person person1 = new Person("李四");
        SessionManager.add(person1);
        Person person2 = new Person("王五");
        SessionManager.add(person2);
        Person person3 = new Person("趙六");
        SessionManager.add(person3);

        person.addChild(person1);
        person1.addChild(person2);
        person1.addChild(person3);
        SessionManager.update(person);
        
//        person.removeChild(person1);
//        SessionManager.update(person);

        SessionManager.close();

    }
}

運行完畢後,查看數據庫中數據,結構以下,知足樹形要求:數據庫

mysql> SELECT * FROM PERSON;
+--------+----------+
| NAME   | PARENTID |
+--------+----------+
| 張三   | NULL     |
| 李四   | 張三     |
| 王五   | 李四     |
| 趙六   | 李四     |
+--------+----------+
4 rows in set (0.00 sec)
相關文章
相關標籤/搜索