Hibernate聯合主鍵映射規則和資料查詢原理

來源:互聯網
上載者:User

Hibernate聯合主鍵的映射規則:

第一種:主鍵和屬性在一個類中

 

1.設定檔

 

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="com.shengsiyuan.hibernate.Student" table="student"><composite-id><key-property name="cardId" column="cardId" type="string"></key-property><key-property name="name" column="name" type="string"></key-property></composite-id><property name="age" column="age" type="integer"></property></class></hibernate-mapping>


註:聯合主鍵的主鍵配置標籤用<composite-id>表示。<key-property表示主鍵。

2.

2. 聯合主鍵的映射規則 

 類中的每個主鍵屬性都對應到資料表中的每個主鍵列。Hibernate要求具有聯合主鍵的實體類實現Serializable介面,並且重寫hashCode與equals方法,重寫這兩個方法的原因在於Hibernate要根據資料庫的聯合主鍵來判斷某兩行記錄是否是一樣的,如果一樣那麼就認為是同一個對象,如果不一樣,那麼就認為是不同的對象。這反映到程式領域中就是根據hashCode與equals方法來判斷某兩個對象是否能夠放到諸如Set這樣的集合當中。聯合主鍵的實體類實現Serializable介面的原因在於使用get或load方法的時候需要先構建出來該實體的對象,並且將查詢依據(聯合主鍵)設定進去,然後作為get或load方法的第二個參數傳進去即可

第二種:主鍵與普通屬性不在同一個類中:

1.設定檔:

<hibernate-mapping> <class name="com.shengsiyuan.hibernate.Student" table="student"> <composite-id name="studentPrimaryKey" class="com.shengsiyuan.hibernate.StudentPrimaryKey"> <key-property name="cardId" column="cardId" type="string"></key-property> <key-property name="name" column="name" type="string"></key-property> </composite-id> <property name="age" column="age" type="integer"></property> </class></hibernate-mapping>


 

 

 將主鍵所對應屬性提取出一個類(稱之為主鍵類),並且主鍵類需要實現Serializable介面,重寫equals方法與hashCode方法,原因與上面一樣。

 

注意:在實體類中,把主鍵類定義為一個變數。在hbm檔案中與第一種的區別在意第一種composite-id》標籤沒有name和class屬性。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.