欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

精通Hibernate:映射一对多关联关系(1)(3)

来源: javaer 分享于  点击 38955 次 点评:103

三、映射一对多双向自身关联关 

Category.java:

  1. package mypack;  
  2. import java.util.HashSet;  
  3. import java.util.Set;  
  4. public class Category  implements java.io.Serializable {  
  5.      private long id;  
  6.      private String name;  
  7.      private Set childCategories = new HashSet(0);  
  8.      private Category parentCategory;  
  9.  
  10.     public Category() {  
  11.     }  
  12.  
  13.     public Category(String name, Set childCategories, Category parentCategory) {  
  14.        this.name = name;  
  15.        this.childCategories = childCategories;  
  16.        this.parentCategory = parentCategory;  
  17.     }  
  18.      
  19.     public long getId() {  
  20.         return this.id;  
  21.     }  
  22.       
  23.     public void setId(long id) {  
  24.         this.id = id;  
  25.     }  
  26.     public String getName() {  
  27.         return this.name;  
  28.     }  
  29.       
  30.     public void setName(String name) {  
  31.         this.name = name;  
  32.     }  
  33.     public Set getChildCategories() {  
  34.         return this.childCategories;  
  35.     }  
  36.       
  37.     public void setChildCategories(Set childCategories) {  
  38.         this.childCategories = childCategories;  
  39.     }  
  40.     public Category getParentCategory() {  
  41.         return this.parentCategory;  
  42.     }  
  43.       
  44.     public void setParentCategory(Category parentCategory) {  
  45.         this.parentCategory = parentCategory;  
  46.     }  

配置文件Category.hbm.xml:

  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping  
  3. PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
  4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping >  
  6.  
  7.   <class name="mypack.Category" table="CATEGORIES" >  
  8.     <id name="id" type="long" column="ID">  
  9.       <generator class="increment"/>  
  10.     </id>  
  11.  
  12.     <property name="name" type="string" >  
  13.         <column name="NAME" length="15" />  
  14.     </property>  
  15.  
  16.     <set   
  17.         name="childCategories" 
  18.         cascade="save-update" 
  19.         inverse="true" 
  20.         >  
  21.         <key column="CATEGORY_ID" />  
  22.         <one-to-many class="mypack.Category" />  
  23.      </set>     
  24.  
  25.    <many-to-one  
  26.         name="parentCategory" 
  27.         column="CATEGORY_ID" 
  28.         class="mypack.Category" 
  29.        />  
  30.  
  31.   </class>  
  32.  
  33. </hibernate-mapping> 


相关栏目:

用户点评