Hibernate中类的继承使用subclass实现


类与表的关系:



*************

Employee.java

*************

package blog.hibernate.domain;

public class Employee {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Employee{" + "id=" + id + ", name=" + name + '}';
    }
}




*************

Sale.java

*************

package blog.hibernate.domain;

public class Sale extends Employee {
    private int sell;

    public int getSell() {
        return sell;
    }

    public void setSell(int sell) {
        this.sell = sell;
    }

    @Override
    public String toString() {
        return "Sale{"  + "id=" + this.getId() + ", name=" + this.getName() + "sell=" + sell + '}';
    }
}




*************

Skill.java

*************

package blog.hibernate.domain;

public class Skill extends Employee{
    private String skiller;

    public String getSkiller() {
        return skiller;
    }

    public void setSkiller(String skiller) {
        this.skiller = skiller;
    }

    @Override
    public String toString() {
        return "Skill{"  + "id=" + this.getId() + ", name=" + this.getName() + "skiller=" + skiller + '}';
    }
}



*************
Employee.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="blog.hibernate.domain">
    <class name="Employee" table="employees" discriminator-value="0">
        <id name="id" column="EMPLOYEE_ID">
            <generator class="native" />
        </id>
        <discriminator column="type" type="int" force="false" />
        <property name="name" column="EMPLOYEE_NAME" />
        
        <subclass name="Sale" discriminator-value="1">
            <property name="sell" column="SELL"/>
        </subclass>
        
        <subclass name="Skill" discriminator-value="2">
            <property name="skiller" column="SKILLER"/>
        </subclass>
    </class>
</hibernate-mapping>




*******************
HibernateUtil.java

*******************

package blog.hibernate;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public final class HibernateUtil {
    
    private static SessionFactory sessionFactory;
    private HibernateUtil(){}
    
    static{
        Configuration cfg = new Configuration();
        sessionFactory =  cfg.configure("hibernate.cfg.xml").buildSessionFactory();
    }
    
    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }
    
    public static Session getSession(){
        return sessionFactory.openSession();
    }





****************
hibernate.cfg.xml

***************

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/extend</property><!-- ///表示连接本机的数据库//localhost:3306 -->
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">1234</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
   		
        <property name="hibernate.hbm2ddl.auto">create</property>
        <property name="hibernate.show_sql">true</property>
                
        <mapping resource="blog/hibernate/domain/Employee.hbm.xml"/>
    </session-factory>	
</hibernate-configuration>


******************

junit test: Extend.java

*******************

package junit.test;

import java.util.logging.Logger;
import java.util.logging.Level;
import org.hibernate.Transaction;
import blog.hibernate.HibernateUtil;
import blog.hibernate.domain.Employee;
import blog.hibernate.domain.Sale;
import blog.hibernate.domain.Skill;
import org.hibernate.Session;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class Extend {

    public Extend() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() {
    }

    @Test
    public void test() {
        add();
        query();
    }

    public void add() {
        Employee emp1 = new Employee();
        emp1.setName("lisi");

        Skill emp2 = new Skill();
        emp2.setName("wangwu");
        emp2.setSkiller("java");

        Sale emp3 = new Sale();
        emp3.setName("sunliu");
        emp3.setSell(300000);

        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtil.getSession();
            tx = session.beginTransaction();
            session.save(emp3);
            session.save(emp2);
            session.save(emp1);
            tx.commit();
        } catch (Exception e) {
            Logger.getLogger(Extend.class.getName()).log(Level.SEVERE, null, e);
            if (tx != null) {
                tx.rollback();
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    public void query() {
        Session session = null;
        try {
            session = HibernateUtil.getSession();
            Employee emp1 = (Employee) session.get(Sale.class, 1);
            Employee emp2 = (Employee) session.get(Skill.class, 2);
            Employee emp3 = (Employee) session.get(Employee.class, 3);
            System.out.println(emp1.toString());
            System.out.println(emp2.toString());
            System.out.println(emp3.toString());
        } catch (Exception e) {
            Logger.getLogger(Extend.class.getName()).log(Level.SEVERE, null, e);
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }
}


用subclass只会生成一张表,表的结构为:

CREATE TABLE `employees` (
  `EMPLOYEE_ID` int(11) NOT NULL auto_increment,
  `type` int(11) NOT NULL,
  `EMPLOYEE_NAME` varchar(255) collate utf8_unicode_ci default NULL,
  `SELL` int(11) default NULL,
  `SKILLER` varchar(255) collate utf8_unicode_ci default NULL,
  PRIMARY KEY  (`EMPLOYEE_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci


employees


Hibernate生成的sql语句为:

Hibernate: insert into employees (EMPLOYEE_NAME, SELL, type) values (?, ?, 1)
Hibernate: insert into employees (EMPLOYEE_NAME, SKILLER, type) values (?, ?, 2)
Hibernate: insert into employees (EMPLOYEE_NAME, type) values (?, 0)

Hibernate:
select
sale0_.EMPLOYEE_ID as EMPLOYEE1_0_0_,
sale0_.EMPLOYEE_NAME as EMPLOYEE3_0_0_,
sale0_.SELL as SELL0_0_
from
employees sale0_
where
sale0_.EMPLOYEE_ID=? and sale0_.type=1

Hibernate:
select
skill0_.EMPLOYEE_ID as EMPLOYEE1_0_0_,
skill0_.EMPLOYEE_NAME as EMPLOYEE3_0_0_,
skill0_.SKILLER as SKILLER0_0_
from
employees skill0_
where
skill0_.EMPLOYEE_ID=? and skill0_.type=2

Hibernate:
select
employee0_.EMPLOYEE_ID as EMPLOYEE1_0_0_,
employee0_.EMPLOYEE_NAME as EMPLOYEE3_0_0_,
employee0_.SELL as SELL0_0_,
employee0_.SKILLER as SKILLER0_0_,
employee0_.type as type0_0_
from
employees employee0_
where
employee0_.EMPLOYEE_ID=?

测试结果为:

Sale{id=1, name=sunliusell=300000}
Skill{id=2, name=wangwuskiller=java}
Employee{id=3, name=lisi}


PS:

采用这种方式的好处是数据处理的效率高;缺点是数据库的表结构不符合关系模型的设计理念,而且子类对应的字段不能强制为非空,如果要新增一个子类那么就必须更改表的结构即新增一列。


posted @ 2012-08-26 21:47  xzf007  阅读(279)  评论(0编辑  收藏  举报