通过many-to-one
元素,可以定义一种常见的与另一个持久化类的关联。 这种关系模型是多对一关联(实际上是一个对象引用-译注):这个表的一个外键引用目标表的 主键字段。
<many-to-one name="propertyName" column="column_name" class="ClassName" cascade="cascade_style" fetch="join|select" update="true|false" insert="true|false" property-ref="propertyNameFromAssociatedClass" access="field|property|ClassName" unique="true|false" not-null="true|false" optimistic-lock="true|false" lazy="proxy|no-proxy|false" not-found="ignore|exception" entity-name="EntityName" formula="arbitrary SQL expression" node="element-name|@attribute-name|element/@attribute|." embed-xml="true|false" index="index_name" unique_key="unique_key_id" foreign-key="foreign_key_name" />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cascade
属性设置为除了none
以外任何有意义的值, 它将把特定的操作传递到关联对象中。这个值就代表着Hibernate基本操作的名称,persist, merge, delete, save-update, evict, replicate, lock, refresh
, 以及特别的值delete-orphan
和all
,并且可以用逗号分隔符 来组合这些操作,例如,cascade="persist,merge,evict"
或cascade="all,delete-orphan"
。更全面的解释请参考第 10.11 节 “传播性持久化(transitive persistence)”. 注意,单值关联 (many-to-one 和 one-to-one 关联) 不支持删除孤儿(orphan delete,删除不再被引用的值).
一个典型的简单many-to-one
定义例子:
<many-to-one name="product" class="Product" column="PRODUCT_ID"/>
property-ref
属性只应该用来对付遗留下来的数据库系统, 可能有外键指向对方关联表的是个非主键字段(但是应该是一个惟一关键字)的情况下。 这是一种十分丑陋的关系模型。比如说,假设Product
类有一个惟一的序列号, 它并不是主键。(unique
属性控制Hibernate通过SchemaExport工具进行的DDL生成。)
<property name="serialNumber" unique="true" type="string" column="SERIAL_NUMBER"/>
那么关于OrderItem
的映射可能是:
<many-to-one name="product" property-ref="serialNumber" column="PRODUCT_SERIAL_NUMBER"/>
当然,我们决不鼓励这种用法。
如果被引用的唯一主键由关联实体的多个属性组成,你应该在名称为<properties>
的元素 里面映射所有关联的属性。
假若被引用的唯一主键是组件的属性,你可以指定属性路径:
<many-to-one name="owner" property-ref="identity.ssn" column="OWNER_SSN"/>
1.如表Class(ClassID,Class_No,ClassName)与Student(StudentID,studentName,Class_No), 其中ClassID,studentID为主键 两个表是一对多的关系,而要求两个通过ClassNo来关联. 而一般的情况下是通过ClassID,放在student表中作为外键. 2.具体的Hibernate的配置文件如下: Class.hbm.xml: <property name="classNo" type="java.lang.String" column="Class_No" length="30" /> <!-- Associations --> <set name="students" lazy="false" inverse="true" cascade="all-delete-orphan" > <key column="Class_No" property-ref="classNo"/> <one-to-many class="Student" /> </set> Student.hbm.xml: <many-to-one name="class" class="Class" not-null="true" property-ref="classNo" > <column name="Class_No" /> </many-to-one> 3.注意点: property-ref属性一般用来解决遗留数据库One To Many关系的问题 property-ref(可选)被关联到此外键的类中的对应属性的名字,若没指定,使用被关联类的主键. property-ref=不是数据库表中的字段名,而是定义的java类中的属性性名,一定要注意.