Hibernate的一对一关联映射
一对一关联映射
一、基于主键的一对一关联映射(双向)
以公民表(tb_people)和身份证表(tb_idcard)为例:
1. People.hbm.xml文件配置 (People类添加 private IDcard idcard;)
<hibernate-mapping> <class name="com.cong.po.People" table="tb_people"> <id name="id" column="id" type="int"> <generator class="native"/> </id> <property name="name" type="string" length="45"> <column name="name"/> </property> <property name="sex" type="string" length="2"> <column name="sex"/> </property> <property name="age" type="int"> <column name="age"/> </property> <one-to-one name="idcard" class="com.cong.po.IDcard" cascade="all"/> </class> </hibernate-mapping>
注:cascade级联关系可以保证主控方所关联的被控方的操作的一致性
例如:主控方进行save、update或delete操作时被控方会进行同样的操作
2.IDcard.hbm.xml文件配置(IDcard类添加 private People people;)
<hibernate-mapping> <class name="com.cong.po.IDcard" table="tb_idcard"> <id name="id" column="id" type="int"> <generator class="foreign"> <param name="property">people</param> </generator> </id> <property name="idcard_code" type="string" length="20" not-null="true"> <column name="IDcard_code"/> </property> <one-to-one name="people" class="com.cong.po.People" constrained="true"/> </class> </hibernate-mapping>
二、基于外键的一对一关联映射
在tb_people中添加一个新字段card_id作为外键,同时保证该字段唯一性
1.People.hbm.xml文件配置(People类添加 private int idcard;)
<hibernate-mapping> <class name="com.cong.po.People" table="tb_people"> <id name="id" column="id" type="int"> <generator class="native"/> </id> <property name="name" type="string" length="45"> <column name="name"/> </property> <property name="sex" type="string" length="2"> <column name="sex"/> </property> <property name="age" type="int"> <column name="age"/> </property> <many-to-one name="card_id" class="com.cong.po.IDcard" unique="true" not-null="true"> <column name="card_id"/> </many-to-one> </class> </hibernate-mapping>
2.IDcard.hbm.xml文件配置(IDcard类添加 private People people;)
<hibernate-mapping> <class name="com.cong.po.IDcard" table="tb_idcard"> <id name="id" column="id" type="int"> <generator class="foreign"> <param name="property">people</param> </generator> </id> <property name="idcard_code" type="string" length="20" not-null="true"> <column name="IDcard_code"/> </property> </class> </hibernate-mapping>
注: 一对一外键关联实际就是多对一关联的一个特例,需要保证外键关联字段的唯一性
在<many-to-one>元素中通过unique属性就可以实现关联字段的唯一性