Hibernate中类的继承使用union-subclass实现
类与表的关系:
*************
Employee.java
*************
employees
sale
skill
插入语句:
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 (?, ?)
查询语句:
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=?
查询结果:
Sale{id=1, name=sunliu, sell=300000}
Skill{id=2, name=wangwu, skiller=java}
Employee{id=3, name=lisi}
PS:使用union-subclass会为每一个类创建一个单独的表(抽象类除外),并且每一个表的主键id的值都是不一样的,这是由于主键生成器使用了hilo的缘故。使用hilo,Hibernate会创建一个名为hibernate_unique_key的表,这个表里存放着主键生成器使用的“高位“,Hibernate会在内存中生成一个低位,然后将高位和低位相加就得到了唯一的主键id,这样就可以保证每个表的id不会重复。
使用这种策略(指使用union-subclass会为每一个类创建一个单独的表)效率是比较低的。这个可以从第三个查询语句看出,这个语句很复杂,主要是它使用了三张表,它将三张表连接起来,使用子查询,用union这种方式将结果连接起来,看哪个不为空,不为空的就是要找的记录;相当于将三张表的记录连接起来,看哪个不为空,只要不为空的就是那条记录了,所以效率还不是很高。