Bidirectional one-to-one correlation mapping
As with one-way mapping, bidirectional mappings can still be implemented in two ways: 1, primary Key Association, 2, unique foreign Key Association
1. Primary Key Association
The mapped relational model is the same as one-way:
The difference between a mapping file and a one-way is that you need to add a <one-to-one> tag to the card to indicate that hibernate will load the associated object user on the primary key. <one-to-one> does not affect storage, only affects loading
User.hbm.xml
[HTML]View Plaincopyprint?
- <? 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">
- <!--use foreign policy to get the primary key of the associated object--
- <generator class="foreign">
- <!--property represents the object to associate--
- <param name="property">card</param>
- </Generator>
- </ID>
- <property name="name" />
- <one-to-one name="card" />
- </class>
- </hibernate-mapping>
Card.hbm.xml
[HTML]View Plaincopyprint?
- <? 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> does not affect storage, only affects load-
- <one-to-one name="person" />
- </class>
- </hibernate-mapping>
2. Unique FOREIGN Key Association
The mapped relational model is the same as one-way:
Map file:
User.hbm.xml
[HTML]View Plaincopyprint?
- <? 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
[HTML]View Plaincopyprint?
- <? 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" />
- <!--must specify <one-to-one>
- The Property-ref attribute in the label is the name of the relationship field-->
- <one-to-one name="person" property-ref="card"/>
[HTML]View Plaincopyprint?
- </class>
- Lt;/hibernate-mapping>
A brief analysis of Hibernate mapping (II.)--Relational mapping (3)