ITEEDU

Chapter 7. 组件(Components)

Component这个概念在Hibernate中几处不同的地方为了不同的目的被重复使用.

7.1. 作为依赖的对象(As Dependent Objects)

Component是一个被包含的对象, 它和它的所有者存储在同一张表中。也就是, 它是一个值类型, 而不是一个实体。 Component术语和组成的面向对象概念相关(而并不是系统构架层次上的组件的概念)。 举个例子, 你可以对一个人 (Person)象以下这样来建模:

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;
    }
    ......
    ......
}
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方法,但是不需要实现任何的接口或申明标识符字段。

以下是这个例子的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类中的一个属性返回包含它的实体的引用。

<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>