雙向一對一關聯映射html
與單向一對一關聯映射同樣,雙向映射依然能夠採用兩種方式實現:一、主鍵關聯;二、惟一外鍵關聯app
一、主鍵關聯spa
映射出的關係模型與單向同樣:.net
映射文件與單向的區別在於:須要在Card加入<one-to-one>標籤,指示hibernate將關聯對象User根據主鍵加載上來。<one-to-one>不影響存儲,隻影響加載hibernate
User.hbm.xmlxml
- <?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="com.jialin.hibernate">
-
- <class name="User">
- <id name="id">
-
- <generator class="foreign">
-
- <param name="property">card</param>
- </generator>
- </id>
- <property name="name" />
-
- <one-to-one name="card" />
- </class>
-
- </hibernate-mapping>
Card.hbm.xmlhtm
- <?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="com.jialin.hibernate">
-
- <class name="Card">
- <id name="id">
- <generator class="native" />
- </id>
- <property name="cardNo" />
-
- <one-to-one name="person" />
-
- </class>
-
- </hibernate-mapping>
二、惟一外鍵關聯對象
映射出的關係模型與單向同樣:blog
映射文件:ip
User.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="com.jialin.hibernate">
-
- <class name="Person">
- <id name="id">
- <generator class="native" />
- </id>
- <property name="name" />
- <many-to-one name="card" unique="true"></many-to-one>
- </class>
-
- </hibernate-mapping>
Card.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="com.jialin.hibernate">
-
- <class name="Card">
- <id name="id">
- <generator class="native" />
- </id>
- <property name="cardNo" />
- <!--必須指定<one-to-one>
- 標籤中的property-ref屬性爲關係字段的名稱-->
- <one-to-one name="person" property-ref="card"/>
- </class>
- lt;/hibernate-mapping>