hibernate映射应用 - 树状结构

@Entity
@Table(name = "t_node")
public class Node {
	private int id;
	private String name;
	private Node parent;
	private Set<Node> childs = new HashSet<Node>();

	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}

	@ManyToOne(cascade={CascadeType.ALL})
	@JoinColumn(name="pId")
	public Node getParent() {
		return parent;
	}
	
	@OneToMany(mappedBy="parent",cascade={CascadeType.ALL},fetch=FetchType.EAGER)
	public Set<Node> getChilds() {
		return childs;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setParent(Node parent) {
		this.parent = parent;
	}

	public void setChilds(Set<Node> childs) {
		this.childs = childs;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
测试代码:
public class NodeTest {
	private static SessionFactory sessionFactory = null;
	@BeforeClass
	public static void beforeClass(){
		sessionFactory = new Configuration().configure().buildSessionFactory();
	}
	
	@Test
	public void testSaveNode(){
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		Node n = new Node();
		n.setName("root");

		Node n1 = new Node();
		n1.setName("n1");

		Node n2 = new Node();
		n2.setName("n2");
		
		Node n3 = new Node();
		n3.setName("n3");
		
		n.getChilds().add(n1);
		n.getChilds().add(n2);
		n2.getChilds().add(n3);

		n.setParent(null);
		n1.setParent(n);
		n2.setParent(n);
		n3.setParent(n2);
		
		session.save(n);
		session.getTransaction().commit();
	}
	
	@Test
	public void testLoadNode(){
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Node n = (Node)session.load(Node.class, 1);
		printNode(n, 0);
		
		session.getTransaction().commit();
	}
	
	public void printNode(Node node, int level){
		String preStr = "";
		for (int i = 0; i < level; i++) {
			preStr += "----";
		}
		System.out.println(preStr + node.getName());
		for (Node n : node.getChilds()) {
			printNode(n, level + 1);
		}
	}
}
运行结果:
root
----n1
----n2
--------n3




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值