以Category类为例,它代表商品类别,存在一对多双向自身关联关系。
在category类中定义两个属性:
.parentCategory:引用父类别的Category对象
.childCategories:引用一组子类别的Category对象
食品类别
/ /
/ /
蔬菜类别 水果类别
| / /
| / /
西红柿类别 苹果类别 桔子类别
Category类的源程序:
package mypack;
import java.io.Serializable;
import java.util.Set;
import java.util.HashSet;
public class Category implements Serializable{
private Long id;
private String name;
private Category,parentCategory;
private Set childCategories = new HashSet();
//此处省略构造方法,以及id和name属性的访问方法
...
public Category getParentCategory(){
return parentCategory;
}
public void setParentCategory(Category parentCategory){
this.parentCategory = parentCategory;
}
public Set getChildCategories(){
return childCategories;
}
public void setChildCategories(Set childCategories){
this.childCategories = childCategories;
}
}
Category类的映射文件Category.hbm.xml:
<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>
<many-to-one name="parentCategory" column="CATEGORY_ID"
class="mypack.Category" />
<set name="childCategories" cascade="save-update" inverse="true">
<key column="CATEGORY_ID"/>
<one-to-many class="mypack.Category"/>
</set>
</class>
</hibernate-mapping>
在category类中定义两个属性:
.parentCategory:引用父类别的Category对象
.childCategories:引用一组子类别的Category对象
食品类别
/ /
/ /
蔬菜类别 水果类别
| / /
| / /
西红柿类别 苹果类别 桔子类别
Category类的源程序:
package mypack;
import java.io.Serializable;
import java.util.Set;
import java.util.HashSet;
public class Category implements Serializable{
private Long id;
private String name;
private Category,parentCategory;
private Set childCategories = new HashSet();
//此处省略构造方法,以及id和name属性的访问方法
...
public Category getParentCategory(){
return parentCategory;
}
public void setParentCategory(Category parentCategory){
this.parentCategory = parentCategory;
}
public Set getChildCategories(){
return childCategories;
}
public void setChildCategories(Set childCategories){
this.childCategories = childCategories;
}
}
Category类的映射文件Category.hbm.xml:
<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>
<many-to-one name="parentCategory" column="CATEGORY_ID"
class="mypack.Category" />
<set name="childCategories" cascade="save-update" inverse="true">
<key column="CATEGORY_ID"/>
<one-to-many class="mypack.Category"/>
</set>
</class>
</hibernate-mapping>