14 继承(一)(整个继承树映射到一张表)

人类(Person) , 男人(Men)继承"人"类, 女人(Women)继承"人"类, UML如下:


14 继承(一)(整个继承树映射到一张表)

映射到如下的t_person表中 , 有以下6个字段:

1 int id //主键

2 varchar name //父类中的姓名

3 int age //父类中的年龄

4 int/varchar type //区分"人","男人","女人" 的专用字段, 默认类型是varchar, 也可以指定为int类型. 叫鉴别器字段

//Person类:type值设为0, Men类: type值设为1, Women 类: type值设为2

5 varchar a //"男人"类专有属性

6 varchar b //"女人"类专有属性

Person, Men, Women 三个类这里就不显示了,但简单, 想看了附件中有源码

Person.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="extends_test.extends_1" auto-import="false">
	<class name="Person" table="t_person" discriminator-value="0"><!-- "鉴别值"为0 -->
		<!-- 父类的属性 -->		
		<id name="id">
			<generator class="native"/>
		</id>	
		<!-- 重点:鉴别器 -->
		<!-- 指定type字段,做区分父子具体类型用 ,各类还要指定"鉴别值": discriminator-value="1"-->
		<discriminator column="type" type="int"/>			
		<!-- 父类的属性 -->
		<property name="name"/>
		<!-- 父类的属性 -->
		<property name="age"/>		
		<!-- Mem子类的映射 -->
		<subclass name="Men" discriminator-value="1"><!-- "鉴别值"为1 -->
			<!-- Men类专有的属性a -->
			<property name="a"/>
		</subclass>
		<!-- Women子类的映射 -->
		<subclass name="Women" discriminator-value="2"><!-- "鉴别值"为2 -->
			<!-- Women类专有的属性b -->
			<property name="b"/>
		</subclass>
	</class>	
</hibernate-mapping>

保存与查询操作:

package extends_test.extends_1;
import org.hibernate.Session;
import org.hibernate.Transaction;
import dao.HibernateUtil;

/**
 * 继承关系的映射(方法一)
 * 
 * 总个继承树映射到一张表
 * 
 */
public class Test
{
	/**
	 * @param args
	 */
	public static void main(final String[] args)
	{
		//add();
		query();
	}
	/**
	 * 查询测试
	 */
	public static void query()
	{
		Session session = null;
		try
		{
			session = HibernateUtil.getSeesion();
			final Person p = (Person) session.get(Person.class, 2); //ID为2的记录是  Men类型
			System.out.println(p.getClass());
			//get()第一个参数用了 Person.class
			//能识别出是class extends_test.extends_1.Men类型
		}
		finally
		{
			if (session != null)
			{
				session.close();
			}
		}
	}

	/**
	 * 添加测试
	 */
	public static void add()
	{
		final Person p1 = new Person();
		p1.setName("我是Person类");
		final Men m1 = new Men();
		m1.setName("我是男人类");
		m1.setA("a");
		final Women w1 = new Women();
		w1.setName("我是女人类");
		w1.setB("b");
		Session session = null;
		try
		{
			session = HibernateUtil.getSeesion();
			final Transaction tx = session.beginTransaction();
			session.save(p1);
			session.save(m1);
			session.save(w1);
			tx.commit();
			//SQL如下 
			//Hibernate: insert into t_person (name, age, type) values (?, ?, 0)
			//Hibernate: insert into t_person (name, age, a, type) values (?, ?, ?, 1)
			//Hibernate: insert into t_person (name, age, b, type) values (?, ?, ?, 2)
		}
		finally
		{
			if (session != null)
			{
				session.close();
			}
		}
	}
}

你可能感兴趣的:(继承)