话不多说,直接上例子,
Husband和Wife之间的一对一关联关系:
Husband持久化类代码:
public class User { private Integer h_id; private String husbandName; private Wife wife; public Integer getH_id() { return h_id; } public void setU_id(Integer h_id) { this.h_id = h_id; } public Wife getWife() { return wife; } public void setWife(Wife wife) { this.wife = wife; } public void setU_id(Integer u_id) { this.u_id = u_id; } public String getHusbandName() { return husbandName; } }
Wife持久化类:
public class Wife { private String wifeName; private Husband husband; private Integer w_id; public Integer getW_id() { return w_id; } public void setW_id(Integer w_id) { this.w_id = w_id; } public String getWifeName() { return wifeName; } public void setWifeName(String wifeName) { this.wifeName = wifeName; } public User getHusband() { return usband; } public void setHusband(Husband husband) { this.husband = husband; } }
一对一关系的配置存在两种方式,一种是通过主键,另外一种是通过唯一外键去关联
配置文件如下:
<hibernate-mapping package="com.lovo"> <class name="Husband" table="t_husband"> <id name="u_id" column="f_user_id" type="integer"> <generator class="identity"></generator> </id> <property name="husbandName" type="string" column="f_husbandName"></property> <!-- 基于主键的一对一--> <!-- 这里就是一对一的映射 --> <one-to-one name="wife" cascade="save-update"></one-to-one>
<!--唯一外键关联的一对一-->
<!--这里我是把huband作为多的一方,column t_husband表中的字段名,表示一个外键-->
<!--设置unique="true"表示唯一性-->
<many-to-one name="wife" class="Wife" column="fk_wife_id" cascade="save-update" unique="true"> </many-to-one>
Wife类映射文件的配置:
<class name="Wife" table="t_wife"> <!-- 基于主键的一对一关系 --> <id column="f_wife_id" name="w_id" type="integer"> <!-- 注意: --> <!-- 本类的id 既是主键,又是外键 --> <!-- Wife对象的是从对象, huband是主对象, 先有主,后有从. --> <!-- 此处的husband是Wife类的一个属性 --> <generator class="foreign"> <param name="property">user</param> </generator> </id> <property name="wifeName" type="string" column="f_wifeName"> </property> <!-- 此处的user是User类的一个属性 --> <!-- constrained="true" 对生成的数据表产生约束,t_wife表的w_id既是主键,又是外键 --> <!-- constrained="false" 表结构上没有约束, 取何值对对象关系没影响,只是对表结构有影响--> <one-to-one name="husband" constrained="true" cascade="save-update"> </one-to-one> </class>
<!--基于外键的一对一--> <one-to-one name="husband" class="Husband" property-ref="wife" cascade="save-update"> </one-to-one>
测试就没写了,参照一对多关系中的例子。