Java代码
package yingjun.model; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity public class Tree { private int id; private String name; private Tree parent; private Set<Tree> children=new HashSet<Tree>(); @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToOne @JoinColumn(name="parent_id") public Tree getParent() { return parent; } public void setParent(Tree parent) { this.parent = parent; } @OneToMany(mappedBy="parent",cascade=CascadeType.ALL,fetch=FetchType.EAGER) public Set<Tree> getChildren() { return children; } public void setChildren(Set<Tree> children) { this.children = children; } }
生成的建表语句:
create table Tree ( id integer not null auto_increment, name varchar(255), parent_id integer, primary key (id) ) alter table Tree add index FK27E7BE9FD80F87 (parent_id), add constraint FK27E7BE9FD80F87 foreign key (parent_id) references Tree (id)
向树中插入数据
@Test public void TestSaveTree(){ Session session=HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Tree tree1=new Tree(); tree1.setName("图片"); Tree tree2=new Tree(); tree2.setName("照片"); Tree tree3=new Tree(); tree3.setName("海报"); Tree tree4=new Tree(); tree4.setName("我的照片1"); Tree tree5=new Tree(); tree5.setName("我的照片2"); tree1.getChildren().add(tree2); tree1.getChildren().add(tree3); tree2.getChildren().add(tree4); tree2.getChildren().add(tree5); tree2.setParent(tree1); tree3.setParent(tree1); tree4.setParent(tree2); tree5.setParent(tree2); session.save(tree1); session.getTransaction().commit(); }
结果:
从树中取入数据代码:
@Test public void TestLoadTree(){ Session session=HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Tree t=(Tree)session.load(Tree.class, 1); print(t); session.getTransaction().commit(); } private void print(Tree tree) { System.out.println(tree.getName()); for(Tree child: tree.getChildren()){ print(child); }
取出结果:
转载出处:
http://www.iteye.com/topic/1129579