Hibernate類的繼承使用joined-class實現

類與表的關係:


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

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">
        <id name="id" column="EMPLOYEE_ID">
            <generator class="native" />
        </id>
        
        <property name="name" column="EMPLOYEE_NAME" />
        
        <joined-subclass name="Sale" table="sale" >
            <key column="SALE_ID" />
            <property name="sell" column="SELL"/>
        </joined-subclass>
        
        <joined-subclass name="Skill" table="skill" >
            <key column="SKILL_ID" />
            <property name="skiller" column="SKILLER"/>
        </joined-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/joinextend</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();
            }
        }
    }        
}



用joined-class會生成三張表:

employees


sale


skill


Hibernate生成的sql語句爲:

Hibernate: insert into employees (EMPLOYEE_NAME) values (?)
Hibernate: insert into sale (SELL, SALE_ID) values (?, ?)
Hibernate: insert into employees (EMPLOYEE_NAME) values (?)
Hibernate: insert into SKILL (SKILLER, SKILL_ID) values (?, ?)
Hibernate: insert into employees (EMPLOYEE_NAME) values (?)

Hibernate:
select
sale0_.SALE_ID as EMPLOYEE1_0_0_,
sale0_1_.EMPLOYEE_NAME as EMPLOYEE2_0_0_,
sale0_.SELL as SELL1_0_
from sale sale0_
inner join
employees sale0_1_
on
sale0_.SALE_ID=sale0_1_.EMPLOYEE_ID
where
sale0_.SALE_ID=?


Hibernate:
select
skill0_.SKILL_ID as EMPLOYEE1_0_0_,
skill0_1_.EMPLOYEE_NAME as EMPLOYEE2_0_0_,
skill0_.SKILLER as SKILLER2_0_
from SKILL skill0_
inner join
employees skill0_1_
on
skill0_.SKILL_ID=skill0_1_.EMPLOYEE_ID
where
skill0_.SKILL_ID=?

測試結果爲:

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



Hibernate:
select
employee0_.EMPLOYEE_ID as EMPLOYEE1_0_0_,
employee0_.EMPLOYEE_NAME as EMPLOYEE2_0_0_,
employee0_1_.SELL as SELL1_0_,
employee0_2_.SKILLER as SKILLER2_0_,
case
when employee0_1_.SALE_ID is not null then 1
when employee0_2_.SKILL_ID is not null then 2
when employee0_.EMPLOYEE_ID is not null then 0
end
as clazz_0_
from
employees employee0_
left outer join
sale employee0_1_
on
employee0_.EMPLOYEE_ID=employee0_1_.SALE_ID
left outer join
SKILL employee0_2_
on
employee0_.EMPLOYEE_ID=employee0_2_.SKILL_ID
where
employee0_.EMPLOYEE_ID=?


PS:

採用這種方式的好處是數據庫的表結構符合關係模型的設計理念子類對應的字段可以強制爲非空,如果要新增一個子類,只需要新增一個表即可;缺點是效率不高,而且表的個數比較多。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章