hibernate一對一唯一外鍵關聯映射(雙向關聯Person<---->IdCard)
一對一唯一外鍵關聯雙向,需要在另一端(idcard),添加<one-to-one>標簽,指示hibernate如何加載
其關聯對象,默認根據主鍵加載person,外鍵關聯映射中,因為兩個實體采用的是person的外鍵維護的關系,
所以不能指定主鍵加載person,而要根據person的外鍵加載,所以采用如下映射方式:
<one-to-one name="person" property-ref="idCard"/>
1、Person的POJO類:
1public class Person {
2
3 private int id;
4
5 private String name;
6
7 private IdCard idCard;
8//省略setter、getter方法
9}
2、IdCard的POJO類:
1public class IdCard {
2
3 private int id;
4
5 private String cardNo;
6
7 private Person person;
8//省略setter、getter方法
9}
3、Person的映射文件Person.hbm.xml
1<?xml version="1.0"?>
2<!DOCTYPE hibernate-mapping PUBLIC
3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
5<hibernate-mapping>
6 <class name="org.apple.hibernate.Person" table="t_person">
7 <id name="id">
8 <generator class="native"/>
9 </id>
10 <property name="name"/>
11 <many-to-one name="idCard" unique="true"/>
12 </class>
13</hibernate-mapping>
4、IdCard的映射文件IdCard.hbm.xml
1<?xml version="1.0"?>
2<!DOCTYPE hibernate-mapping PUBLIC
3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
5<hibernate-mapping>
6 <class name="org.apple.hibernate.IdCard" table="t_idcard">
7 <id name="id">
8 <generator class="native"/>
9 </id>
10 <property name="cardNo"/>
11 <one-to-one name="person" property-ref="idCard"/>
12 </class>
13</hibernate-mapping>