1. 程式人生 > >Hibernate hbm 外來鍵關聯——SSH (Spring+Struts+Hibernate)框架搭建之配置檔案序列六

Hibernate hbm 外來鍵關聯——SSH (Spring+Struts+Hibernate)框架搭建之配置檔案序列六

      hibernate管理資料庫後,bbm.xml的關聯配置很重要,<many-to-one> 與<one-to-many>一定要配置正確      

      繼上次介紹了:

      下面來介紹一下與表的關聯相關的Teacher.hbm.xml的配置

<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
   
<hibernate-mapping package="net.cxiny.po">
   	<class name="Teacher" table="teacher">
   		<id name="tid" column="tid">
   			<generator class="native"/>
   		</id>
   		<property name="name" length="45" not-null="true"/>
   	  	<many-to-one cascade="save-update,persist" name="subject" column="bid" foreign-key="fk_teacher_bid_subject_bid" />
   		<many-to-one cascade="save-update,persist" name="role" column="rid" foreign-key="fk_teacher_rid_role_rid" />
   		<many-to-one cascade="save-update,persist" name="position" column="pid" foreign-key="fk_teacher_pid_position_pid" />
   	</class>
</hibernate-mapping> 
上面的是多對一,用的是<many-to-one>對於職位的外來鍵:fk_teacher_pid_position_pid,即teacher表的pid欄位關聯position表的pid欄位

下面是Position.hbm.xml的相關配置

<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
   
<hibernate-mapping package="net.cxiny.po">
   	<class name="Position" table="position">
   		<id name="pid" column="pid">
   			<generator class="native"/>
   		</id>
   		<property name="pname" length="45" not-null="true"/>
   		<set name="teachers" cascade="save-update,persist">  <!-- 本model中的屬性 -->
   			<!-- Teacher表中的pid屬性值參照Position表中的pid -->
   			<key  column="pid" foreign-key="fk_teacher_pid_position_pid"/>
   			<!-- 一對多,set中放置的是Teacher -->
   			<one-to-many  class="Teacher"/>
   		</set>
   	</class>
</hibernate-mapping>