Hibernate对于继承的关联关系有三种处理方式,一种是将整个继承树的持久化实体在一张表中进行映射,一种是将继承树中的每一个持久化实体在数据库中为其各自建立一张表来进行映射,一种是将继承树的子类在数据库中为其各自建立一张表来进行映射。在这里先来看第一种方式的配置方式。
一。Person
package com.orm.model;
/**
* Created by IntelliJ IDEA.
* User: Zhong Gang
* Date: 10/19/11
* Time: 6:13 PM
*/
public abstract class Person extends DomainObject {
private String name;
protected Person(String name) {
this.name = name;
}
}
二。Male
package com.orm.model;
/**
* Created by IntelliJ IDEA.
* User: Zhong Gang
* Date: 10/19/11
* Time: 6:13 PM
*/
public class Male extends Person {
private String make;
public Male(String name, String make) {
super(name);
this.make = make;
}
}
三。Female
package com.orm.model;
/**
* Created by IntelliJ IDEA.
* User: Zhong Gang
* Date: 10/19/11
* Time: 6:13 PM
*/
public class Female extends Person {
private String maked;
public Female(String name, String maked) {
super(name);
this.maked = maked;
}
}
四。映射配置文件
<?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.Person" table="person" abstract="true"> <id name="id" column="id" type="java.lang.Integer"> <generator class="native"/> </id> <discriminator column="gender" type="java.lang.String"/> <property name="name" column="name" type="java.lang.String"/> <subclass discriminator-value="male" name="com.orm.model.Male"> <property name="make" column="make" type="java.lang.String"/> </subclass> <subclass discriminator-value="female" name="com.orm.model.Female"> <property name="maked" column="maked" type="java.lang.String"/> </subclass> </class> </hibernate-mapping>
五。测试代码
package com.orm;
import com.orm.model.Female;
import com.orm.model.Male;
import com.orm.model.Person;
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 HibernateInheritenceTest 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 testInheritence() throws Exception {
Person male = new Male("male", "go go go");
Person female = new Female("female", "yes yes yes");
coupleService.saveOrUpdate(male);
coupleService.saveOrUpdate(female);
}
}
测试结果及截图
附上源码以供参考