首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Hibernate 3 學習筆記(十六):集合映射全攻略

     編輯:Java 相關知識

Hibernate 支援的集合類型對照表

Java 介面映射標籤資料表特徵特性
Set<set>無索引欄位,主鍵為 (外鍵, 元素值)不重複、無序
List<list>有 <index> 欄位記錄位置有序、可重複
Bag<bag>無索引,主鍵僅外鍵,允許重複無序、可重複
Map<map>有 <map-key> 欄位Key-Value、Key 唯一

1. Set 映射:基本值型別集合

資料表

CREATE TABLE user (id PK, name);
CREATE TABLE email (id FK, address); -- 主鍵 (id, address)

映射

<set name="emails" table="email">
    <key column="id"/>
    <element type="java.lang.String" column="address"/>
</set>

特點:**同一 User 下 Email 不可重複**。

2. List 映射:有序集合

資料表

CREATE TABLE item (id FK, position INT, name); -- 主鍵 (id, position)

映射

<list name="items" table="item">
    <key column="id"/>
    <index column="position"/>
    <element type="java.lang.String" column="name"/>
</list>

插入順序會持久化到 position 欄位,讀取時自動按位置排序。

3. Bag 映射:最鬆散的集合

資料表

CREATE TABLE item (id FK, name); -- 無主鍵,允許完全重複列

映射

<bag name="items" table="item">
    <key column="id"/>
    <element column="name" type="java.lang.String"/>
</bag>

效能陷阱:更新時無法定位具體行,Hibernate 採取 **全刪重寫** 策略:

DELETE FROM item WHERE id=?
INSERT INTO item (id, name) VALUES (?, ?) ...

解決方案:<idbag> 引入代理主鍵

CREATE TABLE item (cid CHAR(32) PK, id FK, name);

<idbag name="items" table="item">
    <collection-id column="cid" type="java.lang.String">
        <generator class="uuid.hex"/>
    </collection-id>
    <key column="id"/>
    <element column="name" type="java.lang.String"/>
</idbag>

更新時可精準 DELETE WHERE cid=?,效能大幅提升。

4. Map 映射:Key-Value 集合

資料表

CREATE TABLE item (id FK, name VARCHAR, price DECIMAL); -- 主鍵 (id, name)

映射

<map name="items" table="item">
    <key column="id"/>
    <map-key column="name" type="java.lang.String"/>
    <element column="price" type="java.math.BigDecimal"/>
</map>

進階主題

Component 集合:元素為自訂類別

使用 <composite-element> 替代 <element>:

<set name="emails" table="email">
    <key column="id"/>
    <composite-element class="com.hb3.pack_15.model.MailAddress">
        <property name="address" column="address"/>
    </composite-element>
</set>

集合排序

  • 資料庫端排序:<set> 加 order-by="address DESC"(需資料庫支援)。
  • 記憶體端排序:實體類別用 SortedSet + 實作 Comparator,映射加 sort="com.xxx.MyComparator"。

延遲載入

集合預設 lazy="true"。存取集合大小或迭代時才發 SQL。
需在 Session 關閉前初始化,或使用 Hibernate.initialize(collection) 強制載入,否則會拋 LazyInitializationException。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved