組件(Component)是一個被包含的對象,在持久化的過程中,它被當作值類型,而并非一個實體的引用。在這篇文檔中,組件這一術語指的是面向對象的合成概念(而并不是系統構架層次上的組件的概念)。舉個例子, 你對人(Person)這個概念可以像下面這樣來建模:
1
public class Person
{
2
private java.util.Date birthday;
3
private Name name;
4
private String key;
5
public String getKey()
{
6
return key;
7
}
8
private void setKey(String key)
{
9
this.key=key;
10
}
11
public java.util.Date getBirthday()
{
12
return birthday;
13
}
14
public void setBirthday(java.util.Date birthday)
{
15
this.birthday = birthday;
16
}
17
public Name getName()
{
18
return name;
19
}
20
public void setName(Name name)
{
21
this.name = name;
22
}
23


24


25
}
26
1
public class Name
{
2
char initial;
3
String first;
4
String last;
5
public String getFirst()
{
6
return first;
7
}
8
void setFirst(String first)
{
9
this.first = first;
10
}
11
public String getLast()
{
12
return last;
13
}
14
void setLast(String last)
{
15
this.last = last;
16
}
17
public char getInitial()
{
18
return initial;
19
}
20
void setInitial(char initial)
{
21
this.initial = initial;
22
}
23
}
24
在持久化的過程中,姓名(Name)
可以作為人(Person)
的一個組件。需要注意的是:你應該為姓名
的持久化屬性定義getter和setter方法,但是你不需要實現任何的接口或申明標識符字段。
以下是這個例子的Hibernate映射文件:
1
<class name="eg.Person" table="person">
2
<id name="Key" column="pid" type="string">
3
<generator class="uuid"/>
4
</id>
5
<property name="birthday" type="date"/>
6
<component name="Name" class="eg.Name"> <!-- class attribute optional -->
7
<property name="initial"/>
8
<property name="first"/>
9
<property name="last"/>
10
</component>
11
</class>
12
人員(Person)表中將包括pid
, birthday
, initial
, first
和 last
等字段。
就像所有的值類型一樣, 組件不支持共享引用。 換句話說,兩個人可能重名,但是兩個Person對象應該包含兩個獨立的Name對象,只不過這兩個Name對象具有“同樣”的值。 組件的值可以為空,其定義如下。 每當Hibernate重新加載一個包含組件的對象,如果該組件的所有字段為空,Hibernate將假定整個組件為空。 在大多數情況下,這樣假定應該是沒有問題的。
組件的屬性可以是任意一種Hibernate類型(包括集合, 多對多關聯, 以及其它組件等等)。嵌套組件不應該被當作一種特殊的應用(Nested components should not be considered an exotic usage)。 Hibernate傾向于支持細致的(fine-grained)對象模型。
<component>
元素還允許有 <parent>
子元素,用來表明component類中的一個屬性是指向包含它的實體的引用。
1
<class name="eg.Person" table="person">
2
<id name="Key" column="pid" type="string">
3
<generator class="uuid"/>
4
</id>
5
<property name="birthday" type="date">
6
<component name="Name" class="eg.Name" unique="true">
7
<parent name="namedPerson"/> <!-- reference back to the Person -->
8
<property name="initial"/>
9
<property name="first"/>
10
<property name="last"/>
11
</component>
12
</class>
13