Hibernate关联映射之一对一双向关联映射

来源:互联网 发布:php xml 编辑:程序博客网 时间:2024/05/09 15:19

1、基于外键的一对一双向关联映射

方法一:使用Annotation实现

(1)建立Husband类和Wife类

package com.model;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.OneToOne;@Entitypublic class Husband {private int id;private String name;private Wife wife;@Idpublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@OneToOnepublic Wife getWife() {return wife;}public void setWife(Wife wife) {this.wife = wife;}}
package com.model;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.OneToOne;@Entitypublic class Wife {private int id;private String name;private Husband husband;@Idpublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@OneToOne(mappedBy="wife")public Husband getHusband() {return husband;}public void setHusband(Husband husband) {this.husband = husband;}}

(2)设置Hibernate配置文件hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- 连接的数据库驱动 --><property name="connection.driver_class">com.mysql.jdbc.Driver</property><!-- 连接的数据库的url --><property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property><!-- 连接的数据库的用户名--><property name="connection.username">root</property><!-- 连接的数据库的密码 --><property name="connection.password"></property><!-- 配置Hibernate数据库方言 --><property name="Dialect">org.hibernate.dialect.MySQLDialect</property><!-- 输出执行的SQL语句 -->        <property name="show_sql">true</property>        <property name="format_sql">true</property><!-- 启动时撤销并重新创建数据库的模式--><property name="hbm2ddl.auto">create</property><property name="current_session_context_class">thread</property><mapping class="com.model.Husband"/><mapping class="com.model.Wife"/></session-factory></hibernate-configuration>

(3)建立测试类,此处使用Junit4进行测试,仅仅测试一对一映射如何建表即可。

package com.test;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;import org.junit.Test;public class ORMappingTest {@Testpublic void test() {Configuration cfg = new Configuration();cfg.configure();ServiceRegistry  sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry(); SessionFactory  sf = cfg.buildSessionFactory(sr);Session s = sf.getCurrentSession();Transaction tx = s.beginTransaction();tx.commit();sf.close();}}

(4)运行测试类,查看后台输出的建表SQL语句。

Hibernate:     create table Husband (        id integer not null,        name varchar(255),        wife_id integer,        primary key (id)    )Hibernate:     create table Wife (        id integer not null,        name varchar(255),        primary key (id)    )Hibernate:     alter table Husband         add index FKAEEA401B9608626C (wife_id),         add constraint FKAEEA401B9608626C         foreign key (wife_id)         references Wife (id)

-----------在双向关联中, 有且仅有一端是作为主体(owner)端存在的:主体端负责维护联接列(即更新). 对于不需要维护这种关系的从表则通过mappedBy属性进行声明.mappedBy的值指向主体的关联属性. 在上面这个例子中,mappedBy的值为wife. 最后,不必也不能再在被关联端Wife定义联接列(husband_id)了,因为已经在主体端进行了声明.

-----------若在Wife类中没有声明mappedBy="wife",则在表Wife中也会生成一个外键husband_id,测试结果为:

Hibernate:     create table Husband (        id integer not null,        name varchar(255),        wife_id integer,        primary key (id)    )Hibernate:     create table Wife (        id integer not null,        name varchar(255),        husband_id integer,        primary key (id)    )Hibernate:     alter table Husband         add index FKAEEA401B9608626C (wife_id),         add constraint FKAEEA401B9608626C         foreign key (wife_id)         references Wife (id)Hibernate:     alter table Wife         add index FK292331C3BF3448 (husband_id),         add constraint FK292331C3BF3448         foreign key (husband_id)         references Husband (id)

--------------------双向关联必设mappedBy-------------------------

方法二:使用映射文件hbm.xml实现:

(1)建立Husband类和Wife类,在方法一的基础上去掉@注解即可。

(2)建立映射文件Husband.hbm.xml和Wife.hbm.xml

<?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="com.model">    <class name="Husband">    <id name="id">    <generator class="native"></generator>    </id>            <property name="name" />   <many-to-one name="wife" column="wife_id" unique="true"></many-to-one>    </class>  </hibernate-mapping>
<?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="com.model">    <class name="Wife">    <id name="id">    <generator class="native"></generator>    </id>            <property name="name" />              <one-to-one name="husband" property-ref="wife"></one-to-one>    </class>  </hibernate-mapping>

(3)设置Hibernate配置文件hibernate.cfg.cml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- 连接的数据库驱动 --><property name="connection.driver_class">com.mysql.jdbc.Driver</property><!-- 连接的数据库的url --><property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property><!-- 连接的数据库的用户名--><property name="connection.username">root</property><!-- 连接的数据库的密码 --><property name="connection.password"></property><!-- 配置Hibernate数据库方言 --><property name="Dialect">org.hibernate.dialect.MySQLDialect</property><!-- 输出执行的SQL语句 -->        <property name="show_sql">true</property>        <property name="format_sql">true</property><!-- 启动时撤销并重新创建数据库的模式--><property name="hbm2ddl.auto">create</property><property name="current_session_context_class">thread</property><mapping resource="com/model/Husband.hbm.xml"/> <mapping resource="com/model/Wife.hbm.xml"/> </session-factory></hibernate-configuration>

(4)运行方法一的测试类,得到相同的测试结果。

2、基于主键的一对一双向关联映射,实际项目中很少应用,这里就不再介绍。

-------------------------------------------------------------------------

Annotation方法可参考hibernate-annotations-3.4.0.GA\doc\reference\zh_cn\html\index.html,使用映射文件方法可参考hibernate-release-4.1.2.Final\documentation\manual\en-US\html\index.html。

原创粉丝点击