標籤:
組件Components
除了粗粒度的物件模型設計(一個表映射成一個持久化類)之外,還可以採用細粒度的物件模型,吧一個表的映射成兩個或者多個類。
被細化出來的類,可以稱為組件(Component)
組件映射
組件映射的單向關聯
組件映射的雙向關聯
組件集合映射
使用組件集合,可以讓組件對象的集合依附於一個持久化對象上
本來說自己寫的,網上看了看資料太全面了 就收集整理好了
Component這個概念在Hibernate中幾處不同的地方為了不同的目的被重複使用.
依賴對象(Dependent objects)
Component是一個被包含的對象,它作為實值型別被持久化,而非一個實體。“component(組件)”這一術語指的是物件導向的合成概念(而並不是系統構架層次上的組件的概念)舉個例子, 你可以對人(Person)如以下這樣來建模:
Java代碼
- public class Person {
- private java.util.Date birthday;
- private Name name;
- private String key;
- public String getKey() {
- return key;
- }
- private void setKey(String key) {
- this.key=key;
- }
- public java.util.Date getBirthday() {
- return birthday;
- }
- public void setBirthday(java.util.Date birthday) {
- this.birthday = birthday;
- }
- public Name getName() {
- return name;
- }
- public void setName(Name name) {
- this.name = name;
- }
- ......
- ......
- }
Java代碼
- public class Name {
- char initial;
- String first;
- String last;
- public String getFirst() {
- return first;
- }
- void setFirst(String first) {
- this.first = first;
- }
- public String getLast() {
- return last;
- }
- void setLast(String last) {
- this.last = last;
- }
- public char getInitial() {
- return initial;
- }
- void setInitial(char initial) {
- this.initial = initial;
- }
- }
現在,姓名(Name)是作為人(Person)的一個組成部分。需要注意的是:需要對姓名 的持久化屬性定義getter和setter方法,但是不需要實現任何的介面或申明標識符欄位。
以下是這個例子的Hibernate對應檔:
Xml代碼
- <class name="eg.Person" table="person">
- <id name="Key" column="pid" type="string">
- <generator class="uuid.hex"/>
- </id>
- <property name="birthday" type="date"/>
- <component name="Name" class="eg.Name"> <!-- class attribute optional -->
- <property name="initial"/>
- <property name="first"/>
- <property name="last"/>
- </component>
- </class>
人員(Person)表中將包括pid, birthday, initial, first和 last等欄位。
就像所有的實值型別一樣, Component不支援共用引用。Component的值為空白從語意學上來講是專有的。 每當 重新載入一個包含組件的對象,如果component的所有欄位為空白,那麼將Hibernate將假定整個component為 空。對於絕大多數目的,這樣假定是沒有問題的。
Component的屬性可以是Hibernate類型(包括Collections, many-to-one 關聯, 以及其它Component 等等)。嵌套Component不應該作為特殊的應用被考慮(Nested components should not be considered an exotic usage)。 Hibernate趨向於支援設計細緻(fine-grained)的物件模型。
<component> 元素還允許有 <parent>子項目 ,用來表明component類中的一個屬性返回包含它的實體的引用。
Xml代碼
- <class name="eg.Person" table="person">
- <id name="Key" column="pid" type="string">
- <generator class="uuid.hex"/>
- </id>
- <property name="birthday" type="date"/>
- <component name="Name" class="eg.Name">
- <parent name="namedPerson"/> <!-- reference back to the Person -->
- <property name="initial"/>
- <property name="first"/>
- <property name="last"/>
- </component>
- </class>
Hibernate組件映射