🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 8.1\. 依赖对象(Dependent objects) 组件(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方法,但是你不需要实现任何的接口或申明标识符字段。 以下是这个例子的Hibernate映射文件: ``` <class name="eg.Person" table="person"> <id name="Key" column="pid" type="string"> <generator class="uuid"/> </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`等字段。 就像所有的值类型一样, 组件不支持共享引用。 换句话说,两个人可能重名,但是两个Person对象应该包含两个独立的Name对象,只不过这两个Name对象具有“同样”的值。 组件的值可以为空,其定义如下。 每当Hibernate重新加载一个包含组件的对象,如果该组件的所有字段为空,Hibernate将假定整个组件为空。 在大多数情况下,这样假定应该是没有问题的。 组件的属性可以是任意一种Hibernate类型(包括集合, 多对多关联, 以及其它组件等等)。嵌套组件不应该被当作一种特殊的应用(Nested components should not be considered an exotic usage)。 Hibernate倾向于支持细致的(fine-grained)对象模型。 `&lt;component&gt;` 元素还允许有 `&lt;parent&gt;`子元素,用来表明component类中的一个属性是指向包含它的实体的引用。 ``` <class name="eg.Person" table="person"> <id name="Key" column="pid" type="string"> <generator class="uuid"/> </id> <property name="birthday" type="date"> <component name="Name" class="eg.Name" unique="true"> <parent name="namedPerson"/> <!-- reference back to the Person --> <property name="initial"/> <property name="first"/> <property name="last"/> </component&gt; </class> ```