三、映射一对多双向自身关联关
Category.java:
- package mypack;
- import java.util.HashSet;
- import java.util.Set;
- publicclass Category implements java.io.Serializable {
- privatelong id;
- private String name;
- private Set childCategories = new HashSet(0);
- private Category parentCategory;
- public Category() {
- }
- public Category(String name, Set childCategories, Category parentCategory) {
- this.name = name;
- this.childCategories = childCategories;
- this.parentCategory = parentCategory;
- }
- publiclong getId() {
- returnthis.id;
- }
- publicvoid setId(long id) {
- this.id = id;
- }
- public String getName() {
- returnthis.name;
- }
- publicvoid setName(String name) {
- this.name = name;
- }
- public Set getChildCategories() {
- returnthis.childCategories;
- }
- publicvoid setChildCategories(Set childCategories) {
- this.childCategories = childCategories;
- }
- public Category getParentCategory() {
- returnthis.parentCategory;
- }
- publicvoid setParentCategory(Category parentCategory) {
- this.parentCategory = parentCategory;
- }
- }
配置文件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 >
- <class name="mypack.Category" table="CATEGORIES" >
- <id name="id" type="long" column="ID">
- <generator class="increment"/>
- </id>
- <property name="name" type="string" >
- <column name="NAME" length="15" />
- </property>
- <set
- name="childCategories"
- cascade="save-update"
- inverse="true"
- >
- <key column="CATEGORY_ID" />
- <one-to-many class="mypack.Category" />
- </set>
- <many-to-one
- name="parentCategory"
- column="CATEGORY_ID"
- class="mypack.Category"
- />
- </class>
- </hibernate-mapping>