Hibernate ORM - 一对接连接表关联关系
Hibernate ORM - 一对一连接表关联关系
对于一对一关联关系的建立,除了前面讲的方式,即将关联关系由某一方维持外,还可以采用另外一种基于第三张表的关联关系方式,即除去两方各自映射的数据表外,再在数据库中建立第三张表用以维持两者的一对一关联关系。下面来看看这是如何实现的吧。
一。Husband
package com.orm.model; /** * Created by IntelliJ IDEA. * User: Zhong Gang * Date: 10/18/11 * Time: 3:23 PM */ public class Husband extends DomainObject { private String name; private Wife wife; public Husband() { } public Husband(String name, Wife wife) { this.name = name; this.wife = wife; } public Husband(String name) { this.name = name; } }
<?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 default-access="field"> <class name="com.orm.model.Husband" table="husband"> <id name="id" column="id" type="java.lang.Integer"> <generator class="native"/> </id> <property name="name" column="name" type="java.lang.String"/> <join table="couple"> <key column="husbandid"/> <many-to-one name="wife" column="wifeid" class="com.orm.model.Wife" cascade="all"/> </join> </class> </hibernate-mapping>
二。Wife
package com.orm.model; /** * Created by IntelliJ IDEA. * User: Zhong Gang * Date: 10/18/11 * Time: 3:23 PM */ public class Wife extends DomainObject { private String name; private Husband husband; public Wife(String name) { this.name = name; } public Wife() { } public Wife(String name, Husband husband) { this.name = name; this.husband = husband; } }
<?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 default-access="field"> <class name="com.orm.model.Wife" table="wife"> <id name="id" column="id" type="java.lang.Integer"> <generator class="native"/> </id> <property name="name" column="name" type="java.lang.String"/> <one-to-one name="husband" class="com.orm.model.Husband"/> </class> </hibernate-mapping>
三。测试代码
package com.orm; import com.orm.model.Husband; import com.orm.model.Wife; import com.orm.service.CoupleService; import junit.framework.TestCase; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by IntelliJ IDEA. * User: Zhong Gang * Date: 10/18/11 * Time: 3:40 PM */ public class HibernateOneToOneTest extends TestCase { private CoupleService coupleService; @Override public void setUp() throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:testDataSource.xml"); coupleService = (CoupleService) context.getBean("coupleService"); } public void testOneToOne() throws Exception { Wife wife = new Wife("wife"); Husband husband = new Husband("husband", wife); coupleService.saveOrUpdate(husband); } }
测试结果截图
这里讲解的是一对一双向的连接表关联关系的建立,如果想要实现单向的关联关系,那么在删除代码中对对方引用的同时需要删除配置文件中的one-to-one元素。最后附上源码以供参考。