对于一对一的关联关系,除了为其中一方的数据表增加外键字段外,另一种做法就是将其中一方的标识符字段即作为主键又作为保持两者一对一关联关系的外键字段。下面来看看,这种做法是如何实现的呢?
一。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"/> <one-to-one name="wife" class="com.orm.model.Wife"/> </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="husbandid" type="java.lang.Integer"> <generator class="foreign"> <param name="property">husband</param> </generator> </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 {
Husband husband = new Husband("husband");
coupleService.saveOrUpdate(husband);
Wife wife = new Wife("wife", husband);
coupleService.saveOrUpdate(wife);
}
}
测试结果截图
这里讲解的是一对一双向主键关联关系,如果你需要的是单向的,那么删除任何一方的one-to-one元素的同时删除代码中对于对方的引用即可,但请记住如果你想使两方中的某一方来维持一对一的关联关系,那么就需要像在Wife的配置文件中设置Wife的标识符一样进行合理的设置。最后附上源码以供参考。