精通Hibernate:映射一对多关联关系(1)(3)
分享于 点击 38955 次 点评:103
三、映射一对多双向自身关联关
Category.java:
- package mypack;
- import java.util.HashSet;
- import java.util.Set;
- public class Category implements java.io.Serializable {
- private long 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;
- }
- public long getId() {
- return this.id;
- }
- public void setId(long id) {
- this.id = id;
- }
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Set getChildCategories() {
- return this.childCategories;
- }
- public void setChildCategories(Set childCategories) {
- this.childCategories = childCategories;
- }
- public Category getParentCategory() {
- return this.parentCategory;
- }
- public void 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>
用户点评