日期:2014-05-16 浏览次数:20722 次
双向一对一关联映射
与单向一对一关联映射一样,双向映射依然可以采用两种方式实现:1、主键关联;2、唯一外键关联
1、主键关联
映射出的关系模型与单向一样:
映射文件与单向的区别在于:需要在Card加入<one-to-one>标签,指示hibernate将关联对象User根据主键加载上来。<one-to-one>不影响存储,只影响加载
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="User"> <id name="id"> <!--采用foreign策略,可以取得关联对象的主键 --> <generator class="foreign"> <!--property代表要关联的对象 --> <param name="property">card</param> </generator> </id> <property name="name" /> <one-to-one name="card" /> </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>不影响存储,只影响加载--> <one-to-one name="person" /> </class> </hibernate-mapping>
2、唯一外键关联
映射出的关系模型与单向一样:
映射文件:
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> </hibernate-mapping>
下篇继续