![](/img/trans.png)
[英]How can I improve the performance when using TABLE_PER_CLASS that causes several lot of tables in a queries?
[英]How to improve performance in Hibernate polymorphic query when using table per class strategy?
按 class 策略使用表時,多態查詢如下所示:
SELECT <some cols>
FROM
(
SELECT
parent_id,
entity1_col,
entity2_col,
1 as clazz_
FROM
entity_table1
UNION
SELECT
parent_id,
entity1_col,
entity2_col,
2 as clazz_
FROM
entity_table2
) abstract_entity
WHERE
abstract_entity.parent_id = X
我們可以看到,如果 entity_table1 和 entity_table2 中有很多行,則此查詢可能會導致性能問題。
我正在使用 Spring-data 和 Hibernate 並且在獲取父實體上的 OneToMany 關系時會生成此請求。
我的問題是:為什么 Hibernate 會生成這樣的請求,盡管它限制了 entity_table1 和 entity_table2 共有的 parent_id 上的選定行?
有沒有辦法讓 Hibernate 生成一個 SQL 請求,如下所示:
SELECT <some cols>
FROM
(
SELECT
parent_id,
entity1_col,
entity2_col,
1 as clazz_
FROM
entity_table1
WHERE
parent_id=X
UNION
SELECT
parent_id,
entity1_col,
entity2_col,
2 as clazz_
FROM
entity_table2
WHERE
parent_id=X
) abstract_entity
FROM 中的每個請求中都有“WHERE parent_id=X”? 這樣在獲取父實體上的關系時不會出現性能問題。
謝謝 !
我根據 hibernate 5.6.3 進行了修改,以在使用每個 class 策略的表時下推多態查詢的預測。 請參考https://github.com/kerler/hibernate-orm/tree/main_5.6.3-open-care 。
修改后,對於代碼“Query q = s.createQuery("from Being h where h.identity =:name1 or h.identity =:name2 or h.identity =:name2" );” in hibernate UT case UnionSubclassTest.java::testNestedUnionedSubclasses(), the SQL generated by hibernate is like:
00:37:43,945 DEBUG SQL:144 -
select
being0_.bid as bid1_2_,
being0_.ident as ident2_2_,
being0_.location as location3_2_,
being0_.sex as sex1_6_,
being0_.salary as salary1_4_,
being0_.species as species1_0_,
being0_.hive as hive2_0_,
being0_.clazz_ as clazz_
from
( select
bid,
ident,
location,
sex,
salary,
null as species,
null as hive,
2 as clazz_
from
employees
where
ident=?
or ident=?
or ident=?
union
all select
bid,
ident,
location,
sex,
null as salary,
null as species,
null as hive,
1 as clazz_
from
humans
where
ident=?
or ident=?
or ident=?
union
all select
bid,
ident,
location,
null as sex,
null as salary,
species,
hive,
3 as clazz_
from
aliens
where
ident=?
or ident=?
or ident=?
) being0_
where
being0_.ident=?
or being0_.ident=?
or being0_.ident=?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.