Hibernate 的關係映射3 One2Many

來源:互聯網
上載者:User

一對多關聯(學生與所修課程的關係)

多對一關聯映射:是在多的一端添加一個外鍵維護多指向一的關聯引用

一對多關聯映射:是在多的一端添加一個外鍵維護一指向多的關聯引用

也就是說,一對多和多對一的映射策略是一致的,只是站的角度不同

單向關聯

缺點:

更新student表中的classid欄位時,需要對每一個student發出一個update的sql來更新classid欄位

如果將t_student表中的classid設定為非空,則不能儲存student資料,因為關係是由classes維護的,在儲存student時,還沒有對應的classid被產生。

Hibernate: insert into t_student (name) values (?)

Hibernate: update t_student set classid=? where id=?

Classes.hbm.xml

<hibernate-mapping>

    <class name="com.hibernate.onetomany1.Classes" table="t_classes">

       <id name="id">

           <generator class="native"/>

       </id>

       <property name="name"/>

        <set name="students">

           <key column="classid"/>

           <one-to-many class="com.hibernate.onetomany1.Student"/>

       </set>

    </class>

</hibernate-mapping>

Student.hbm.xml

<hibernate-mapping>

    <class name="com.hibernate.onetomany1.Student" table="t_student">

       <id name="id">

           <generator class="native"/>

       </id>

       <property name="name"/>

    </class>

</hibernate-mapping>

 

雙向關聯

一對多雙向關聯映射的方法:

在一的一端:在集合標籤裡面使用<key>標籤來表明需要在對方的表中添加一個外鍵指向一的一端。

在多的一端:使用<many-to-one>標籤來映射。

需要注意:<key>標籤所指定的外鍵欄位名需要與<many-to-one>標籤定義的外鍵欄位名一致,否則便會造成引用資料的

丟失!

注意:

如果從一端來維護一對多雙向關聯的關係,hibernate會發出多餘的update語句,所以

一般地情況下,我們便會從多一端來維護其關聯關係。

Classes.hbm.xml

<hibernate-mapping>

    <class name="com.hibernate.onetomany2.Classes" table="t_classes2">

       <id name="id">

           <generator class="native"/>

       </id>

       <property name="name"/>

        <set name="students" >

           <key column="classid"/>

           <one-to-many class="com.hibernate.onetomany2.Student"/>

       </set>

    </class>

</hibernate-mapping>

Student.hbm.xml

<hibernate-mapping>

    <class name="com.hibernate.onetomany2.Student" table="t_student2">

       <id name="id">

           <generator class="native"/>

       </id>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.