天天看點

hibernate類之間繼承關系映射

1.示圖

hibernate類之間繼承關系映射

2.Animal.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">
 <!-- Generated 2016-7-20 10:48:06 by Hibernate Tools 3.4.0.CR1 -->
 <hibernate-mapping>
      <class name="com.eduask.pojo.Animal" table="Animal">
         <id name="id" type="int">
             <column name="ID" />
             <generator class="assigned"/>
         </id>
         <discriminator column="age" type="string"></discriminator>
          <property name="name" type="java.lang.String">
          <column name="NAME" />
         </property>
         <!--使用subclass時必定使用discriminator,且放在id下面  -->
         <subclass name="com.eduask.pojo.Cat" discriminator-value="10">
         <property name="color"></property>
         </subclass>
         <!--使用union-subclass -->
         <!-- <union-subclass name="com.eduask.pojo.Cat" table="Cat">
         <property name="color"></property>
         </union-subclass> 
         -->
         </class>
 </hibernate-mapping>      

3.CatTest.java

package com.eduask.test;


 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.Transaction;
 import org.junit.Before;
 import org.junit.Test;


 import com.eduask.pojo.Cat;
 import com.eduask.util.HibernateUtil;


 public class CatTest {
 private SessionFactory sessionFactory;
 @Before
 public void setUp(){
sessionFactory=HibernateUtil.getSessionFactory();
  }
 @Test
 public void catTest(){
Session session=sessionFactory.openSession();
Transaction tr=session.beginTransaction();
Cat c=new Cat();
c.setName("小貓之一");
c.setColor("black");
session.save(c);
tr.commit();
session.close();
 }
 }      

4.使用subclass程式運作之後,檢視資料庫如下: