Hibernate中种的继承联合使用subclass和join

Hibernate中类的继承联合使用subclass和join

类和表的关系:

单独使用<subclass/>元素的类会和父类在同一张表里;

使用<subclass><join></join></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">
            <join table="skill" >
                <key column="id" />
                <property name="skiller" column="SKILLER"/>
            </join>
        </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/unionextend</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: JoinExtend.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 JoinExtend {
    
    public JoinExtend() {
    }

    @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(JoinExtend.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(JoinExtend.class.getName()).log(Level.SEVERE, null, e);
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }        
}

生成的表结构:

employees

Hibernate中种的继承联合使用subclass和join


skill

Hibernate中种的继承联合使用subclass和join


插入语句:

Sale
Hibernate: insert into employees (EMPLOYEE_NAME, SELL, type) values (?, ?, 1)

Skill
Hibernate: insert into employees (EMPLOYEE_NAME, type) values (?, 2)
Hibernate: insert into skill (SKILLER, id) values (?, ?)

Employee
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_1_.SKILLER as SKILLER1_0_
from employees skill0_
inner join skill skill0_1_
on skill0_.EMPLOYEE_ID=skill0_1_.id
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_1_.SKILLER as SKILLER1_0_,
employee0_.type as type0_0_
from employees employee0_
left outer join skill employee0_1_
on employee0_.EMPLOYEE_ID=employee0_1_.id
where employee0_.EMPLOYEE_ID=?


查询结果:
Sale{id=1, name=sunliu, sell=300000}
Skill{id=2, name=wangwu, skiller=java}

Employee{id=3, name=lisi}


PS:这样联合使用subclass和join的好处是结合了单独使用subclass的高效率和joined-subclass的对于关系模型的理念。如果类的属性比较多则用join,如果属性少则直接用subclass即可(指用本案例的模型)。