Hibernate中双向关联中的一对一关联有两种形式:
以员工表和身份证号表为例
1. 员工中有员工的编号,姓名。
private int id;
private String name;
private IdCard idCard;
身份证号表中有编号,身份证号。
private int id;
private Date userfulLife;
private Person person;
但是其中身份证号表中的id既是主键又是外键。
那么在员工表的映射文件Person.hbm.xml中的配置如下
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.itcast.hibernate.domain">
<class name="Person">
<id name="id" column="person_id">
<generator class="native"/>
</id>
<property name="name" column="person_name"/>
<one-to-one name="idCard" />
</class>
</hibernate-mapping>
身份证号表映射文件IdCard.hbm.xml配置如下
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.itcast.hibernate.domain">
<class name="IdCard" table="id_card">
<!-- id既是主键又是外键 -->
<id name="id" column="personID">
<generator class="foreign">
<param name="property">person</param>
</generator>
</id>
<property name="userfulLife" column="userful_life"/>
<!-- constrained="true"添加外键约束 -->
<one-to-one name="person" class="Person" constrained="true"/>
</hibernate-mapping>
/*********************************************************************************/
2. 第二种形式就是
表结构不变,注意这时身份证号表中的id是主键但不是外键,外键是另一个字段personId。
这样的话xml文件如何配置呢?
首先是Person.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.itcast.hibernate.domain">
<class name="Person">
<id name="id" column="person_id">
<generator class="native"/>
</id>
<property name="name" column="person_name"/>
<one-to-one name="idCard" property-ref="person" />
</class>
</hibernate-mapping>
接下来就是IdCard.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.itcast.hibernate.domain">
<class name="IdCard" table="id_card">
<id name="id">
<generator class="native" />
</id>
<property name="userfulLife" column="userful_life"/>
<many-to-one name="person" unique="true" not-null="true" column="person_id"></many-to-one>
</class>
</hibernate-mapping>