hibernate:One-to-one关系映射 [图片]
对于hibernate的one-to-one关系来说,大家常常把它忽略,认为它很简单,其实这里面有些细节需要注意,在hibernate3中有两种实现one-to-one的方法:第一种就是用many-to-one来代替一对多,其实one-to-one也就是many-to-one的一种极限方式,若把many-to-one设置unique="true",则这时候的many-to-one实质上就是one-to-one;这里为什么能够用many-to-one来代替one-to-one呢?最根本的是两个对象必须有一个字段相关联,那么你也发现one-to-one中没有column属性,也就是不能够把one-to-one的这种关系生成一个字段/属性,而many-to-one可以,它有column属性。所以,说了这么多,你应该明白为什么可以用many-to-one来代替one-to-one.
对于这种方法要注意几点:
例如,下面的介绍中use中的两个字段同时影射adress,只能够实现单向one-to-one,也就是从use到adress,不能够实现从adress到use.然但下面也介绍了可以使用复杂的方法来解决,但是得不偿失。
第二种方法:基于主键关联的one-to-one,这种方法比较直接。也就是让adress的主键值和use的一样就可以了,通过
<id name="id" column="ADDRESS_ID">
<generator makes sense for this association, since deletion of the User should result in deletion of the Address. (Remember that Address now has its own entity lifecycle.)
Our database schema still allows duplicate values in the BILLING_ADDRESS_ID column of the USER table, so two users could have a reference to the same address. To make this association truly one-to-one, we add unique="true" to the <many-toone> element, constraining the relational model so that there can be only one user per address:
<many-to-one name="billingAddress"
/>
To finish the mapping, we have to map the homeAddress property of User. This is easy enough: we add another <many-to-one> element to the User metadata, mapping a new foreign key column, HOME_ADDRESS_ID:
<many-to-one name="homeAddress"
table="ADDRESS">
<id name="id" column="ADDRESS_ID">
<generator class="foreign">
<param name="property">user</param>
</generator>
</id>
...
<one-to-one name="user"
class="User"
constrained="true"/>
</class>
The <param> named property of the foreign generator allows us to name a one-toone association of the Address class—in this case, the user association. The foreign generator inspects the associated object (the User) and uses its identifier as the identifier of the new Address. Look at the table structure in figure 6.8. The code to create the object association is unchanged for a primary key association; it’s the same code we used earlier for the many-to-one mapping style.