●基于外键的一对一关联:
假设范例User与Room是一对一的关系,也就是每一个人分配一个房间,先看看这两个类:
代码: User.java
package com.xtedu.teach.hibernate.mappings;
public class User {
private long id;
private String name;
private Room room;
}
代码: Room.java
package com.xtedu.teach.hibernate.mappings;
public class Room {
private long id;
private String address;
private User user;
}
要映射User与Room的一对一关系,我们可以有两种方式,一种是通过外键参考,在之前的多对一的例子中即使外键参考的例子,我们现在限制多对一为一对一,只要在User.hbm.xml中的<many-to-one>上加上unique="true",表示限制一个User有一独有的Room:
代码:
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.User" table="USER">
<id name="id" column="USER_ID" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="name">
<column name="NAME" length="16" not-null="true"/>
</property>
<many-to-one name="room"
column="ROOM_ID"
class="com.Room"
cascade="all"
unique="true"/>
</class>
</hibernate-mapping>
这就完成了单向的一对一映射,我们可以在Room.hbm.xml上加入参考回User的设定,使其成为双向的一对一映射,如下:
代码:
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.Room" table="ROOM">
<id name="id" column="ROOM_ID" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="address" type="string"/>
<one-to-one name="user"
class="com.User"
property-ref="room"/>
</class>
</hibernate-mapping>
在<one-to-one>的设定中,我们告诉Hibernate,Room返向参考回User的room属性。
● 基于主键的一对一关联:限制两个数据表的主键使用相同的值.
如此一个User与Room就是一对一关系,在User.hbm.xml这儿,只要使用<one-to-one>设定关联即可:
代码:
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.User" table="USER">
<id name="id" column="USER_ID" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="name">
<column name="NAME" length="16" not-null="true"/>
</property>
<one-to-one name="room"
class="com.Room"
cascade="all"/>
</class>
在Room.hbm.xml这儿,必须限制其主键与User的主键相同,而在属性上,使用constrained="true"告诉Hibernate参考至User的主键:
代码:
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.Room" table="ROOM">
<id name="id" column="ROOM_ID" unsaved-value="0">
<generator class="foreign">
<param name="property">user</param>
</generator>
</id>
<property name="address" type="string"/>
<one-to-one name="user"
class="com.User"
constrained="true"/>
</class>
</hibernate-mapping>