分类:一对多自身双向关联关系
Java持久化类:
package com.hyy.hibernate.one_to_many.domain; import java.util.HashSet; import java.util.Set; /** * 分类:一对多自身双向关联关系 * User: HYY * Date: 13-12-13 * Time: 下午7:32 * To change this template use File | Settings | File Templates. */ public class Category { private Integer id; private String name; private Category parent; private Set<Category> children = new HashSet<Category>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getParent() { return parent; } public void setParent(Category parent) { this.parent = parent; } public Set<Category> getChildren() { return children; } public void setChildren(Set<Category> children) { this.children = children; } }
Category.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.hyy.hibernate.one_to_many.domain"> <class name="Category" dynamic-update="true"> <id name="id"> <generator class="native"/> </id> <property name="name" length="50" access="property"/> <many-to-one name="parent" column="parent_id" /> <set name="children" inverse="true" cascade="save-update" lazy="true"> <key column="parent_id"/> <one-to-many class="Category"/> </set> </class> </hibernate-mapping>
一对多关联关系的one-to-many和many-to-one标签中的外键名要相同,比如本例的parent_id,一定是这两个,不能是其他了。
测试类:
public class CategoryTest { @Test public void test1() { //食物 Category food = new Category(); food.setName("food"); //水果 Category fruit = new Category(); fruit.setName("fruit"); fruit.setParent(food); food.getChildren().add(fruit); //蔬菜 Category veg = new Category(); veg.setName("veg"); veg.setParent(food); food.getChildren().add(veg); //苹果 Category apple = new Category(); apple.setName("apple"); apple.setParent(fruit); fruit.getChildren().add(apple); Session session = HibernateUtil.getSession(); session.beginTransaction(); session.save(food); session.getTransaction().commit(); } }