实例分析如下:
package com.java1234.model;
import java.util.HashSet;
import java.util.Set;
public class Node {
private long id;
private String name;
private Node parentNode;
private Set<Node> childNodes=new HashSet<Node>();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Node getParentNode() {
return parentNode;
}
public void setParentNode(Node parentNode) {
this.parentNode = parentNode;
}
public Set<Node> getChildNodes() {
return childNodes;
}
public void setChildNodes(Set<Node> childNodes) {
this.childNodes = childNodes;
}
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.java1234.model">
<class name="Node" table="t_node">
<id name="id" column="nodeId">
<generator class="native"></generator>
</id>
<property name="name" column="nodeName"></property>
<many-to-one name="parentNode" column="parentId" class="com.java1234.model.Node" cascade="save-update"></many-to-one>
<set name="childNodes" inverse="true">
<key column="parentId"></key>
<one-to-many class="com.java1234.model.Node"/>
</set>
</class>
</hibernate-mapping>
package com.java1234.service;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.java1234.model.Node;
import com.java1234.util.HibernateUtil;
public class NodeTest {
private SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
private Session session;
@Before
public void setUp() throws Exception {
session=sessionFactory.openSession(); // 生成一个session
session.beginTransaction(); // 开启事务
}
@After
public void tearDown() throws Exception {
session.getTransaction().commit(); // 提交事务
session.close(); // 关闭session
}
@Test
public void testSaveMenu() {
Node node=new Node();
node.setName("根节点");
Node subNode1=new Node();
subNode1.setName("子节点1");
Node subNode2=new Node();
subNode2.setName("子节点2");
subNode1.setParentNode(node);
subNode2.setParentNode(node);
session.save(subNode1);
session.save(subNode2);
}
}