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>


 



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。