The inheritance of classes in Hibernate is implemented using Union-subclass

Source: Internet
Author: User
Tags generator inheritance

class-to-table relationships:


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

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 () + "s Ell= "+ 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 ">


*******************
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.sourceforg E.net/hibernate-configuration-3.0.dtd ">  


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

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 () throw
    S 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 ();
 }
        }
    }        
}



The resulting table structure:

Hibernate_unique_key


Employees

Sale

Skill


INSERT statement:

Hibernate:insert into SALE (Employee_Name, SELL, employee_id) VALUES (?,?,?)
Hibernate:insert into SKILL (Employee_Name, Skiller, employee_id) VALUES (?,?,?)
Hibernate:insert into employees (Employee_Name, employee_id) VALUES (?,?)


Query statement:


Hibernate:
Select Sale0_. employee_id as employee1_0_0_,
sale0_. Employee_Name as employee2_0_0_,
sale0_. SELL as Sell1_0_
From SALE sale0_
where sale0_. Employee_id=?


Hibernate:
Select Skill0_. employee_id as employee1_0_0_,
skill0_. Employee_Name as employee2_0_0_,
skill0_. Skiller as Skiller2_0_
From SKILL skill0_
where skill0_. Employee_id=?


Hibernate:
Select Employee0_. employee_id as employee1_0_0_,
employee0_. Employee_Name as employee2_0_0_,
employee0_. SELL as sell1_0_,
employee0_. Skiller as skiller2_0_,
Employee0_.clazz_ as Clazz_0_
From
(
Select NULL as SELL,
Null as Skiller,
EMPLOYEE_ID,
Employee_Name,
0 as Clazz_
From Employees
Union
Select SELL,
Null as Skiller,
EMPLOYEE_ID,
Employee_Name,
1 as Clazz_
From SALE
Union
Select NULL as SELL,
Skiller,
EMPLOYEE_ID,
Employee_Name,
2 as Clazz_
From SKILL
)
employee0_
where employee0_. Employee_id=?


Query Result:

Sale{id=1, Name=sunliu, sell=300000}
skill{id=2, Name=wangwu, Skiller=java}
Employee{id=3, Name=lisi}


PS: Using Union-subclass creates a separate table for each class (except the abstract class), and the value of the primary key ID for each table is different, because the primary key generator uses Hilo. Using hilo,hibernate creates a table named Hibernate_unique_key, which holds the "high" that the primary key generator uses, Hibernate generates a low in memory, and then adds the highs and lows together to get a unique primary key ID. This guarantees that the ID of each table will not be duplicated.

Using this strategy (meaning that using union-subclass to create a separate table for each class) is less efficient. This can be seen from the third query statement, the statement is very complex, mainly it uses three tables, it connects three tables, using sub-query, union this way to connect the results, to see which is not empty, is not empty is to find the record; the equivalent of three tables of records connected to see which is not empty, As long as the non-empty is the record, so the efficiency is not very high.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.