Hibernate的List映射

来源:互联网 发布:puppy linux关机保存 编辑:程序博客网 时间:2024/06/05 11:50
Answer类为Question类一对多关联关系,即一个问题对应多个答案。他们的表结构如下 
 
如果希望Answer集合在Question类中作为List存储,我们可以使用hibernate的list或者bag标签来进行映射。 

当使用list标签映射时,Question.hbm.xml中的配置如下: 
Java代码  收藏代码
  1. <hibernate-mapping>  
  2.     <class name="mypackage.Question" table="question">  
  3.         <id name="id" type="integer">  
  4.             <column name="id" />  
  5.             <generator class="identity" />  
  6.         </id>  
  7.         <property name="userId" type="integer">  
  8.             <column name="user_id" />  
  9.         </property>  
  10.         <property name="content" type="string">  
  11.             <column name="content" length="200" />  
  12.         </property>  
  13.         <property name="time" type="timestamp">  
  14.             <column name="time" length="19" />  
  15.         </property>  
  16.         <list name="answers" inverse="true" cascade="all" lazy="false">  
  17.             <key column="question_id" not-null="true"/>  
  18.             <index column="position" />  
  19.             <one-to-many class="com.skyseminar.meeting.db.TMeetingAnswer"/>  
  20.         </list>  
  21.     </class>  
  22. </hibernate-mapping>  
list标签中,key元素表示Answer表通过外键question_id参照Question表。 
因List集合是个有序的集合,所以要使用<index column="position"/>来标明其顺序。(position为Answer表中附加字段) 
因此在插入更新时便需要维护position字段,否则索引设置错误,取出的数据就会出现空值情况。 

而是用bag标签映射list集合,则无需维护多余的字段。因此使用Hibernate进行一对多映射时,选择使用bag标签更佳。值得注意的是bag集合对象为无序排列,如果需要排序,可以使用order-by标签。 
bag标签使用格式如下: 
Java代码  收藏代码
  1. <bag name="answers" order-by="id asc" lazy="false">  
  2.     <key column="question_id" />  
  3.     <one-to-many class="mypackage.Answer"/>  
  4. </bag>  
0 0