浅析Hibernate映射(二)——关系映射(3)
双向一对一关联映射
与单向一对一关联映射一样,双向映射依然可以采用两种方式实现: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>
- lt;/hibernate-mapping>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。