首页 > 代码库 > Hibernate-----一对一唯一外键关联映射(映射文件方式)

Hibernate-----一对一唯一外键关联映射(映射文件方式)

唯一外键关联:外键关联,本来是用于多对一的配置,但如果加上唯一的限制后,也可用来表示一对一关联关系;是多对一的特例

 

一、单向关联映射

One(维护端:Person)[‘多端’]

<?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 package="org.app.model">
    <class name="Person" table="t_person">
       <id name="id">
           <generator class="increment"/>
       </id>
       <property name="name"/>
 
       <!—维护关系:在本端添加一个外键idCard_id指向idCard,并添加唯一属性实现一对一 -->
       <many-to-one name="idCard" column="idCard_id"unique="true" />
    </class>
</hibernate-mapping>

To

One(非维护端:IdCard)[‘一端’]

<?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 package="org.app.model">
    <class name="IdCard" table="t_idCard">
       <id name="id">
           <generator class="increment"/>
       </id>
       <property name="cardNo"/>
    </class>
</hibernate-mapping>


 


二、双向关联映射

One(维护端:Person)[‘多端’]

<?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 package="org.app.model">
    <class name="Person" table="t_person">
       <id name="id">
           <generator class="increment"/>
       </id>
       <property name="name"/>
 
       <many-to-one name="idCard"column="idCard_id" unique="true" />
    </class>
</hibernate-mapping>

To

One(非维护端:IdCard)[‘一端’]

<?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 package="org.app.model">
    <class name="IdCard" table="t_idCard">
       <id name="id">
           <generator class="increment"/>
       </id>
       <property name="cardNo"/>
 
       <!-- property-ref:表示根据Person的idCard外键添加 -->
       <one-to-one name="person"property-ref="idCard"></one-to-one>
    </class>
</hibernate-mapping>


 



Hibernate-----一对一唯一外键关联映射(映射文件方式)