gpt4 book ai didi

java - Hibernate Union 替代方案

转载 作者:IT老高 更新时间:2023-10-28 20:27:50 30 4
gpt4 key购买 nike

使用 hibernate 实现联合查询有哪些替代方法?我知道hibernate目前不支持联合查询,现在我看到的唯一方法是使用 View 表。

另一种选择是使用纯 jdbc,但这样我会丢失所有示例/条件查询的好处,以及 hibernate 对表/列执行的 hibernate 映射验证。

最佳答案

您可以使用 id in (select id from ...) 或 id in (select id from ...)

例如而不是不工作

from Person p where p.name="Joe"
union
from Person p join p.children c where c.name="Joe"

你可以的

from Person p 
where p.id in (select p1.id from Person p1 where p1.name="Joe")
or p.id in (select p2.id from Person p2 join p2.children c where c.name="Joe");

不过,至少在使用 MySQL 之后,您会遇到性能问题。有时,对两个查询进行穷人联接会更容易:

// use set for uniqueness
Set<Person> people = new HashSet<Person>((List<Person>) query1.list());
people.addAll((List<Person>) query2.list());
return new ArrayList<Person>(people);

执行两个简单的查询通常比执行一个复杂的查询要好。

编辑:

举个例子,这里是来自子选择解决方案的 MySQL 查询的 EXPLAIN 输出:

mysql> explain 
select p.* from PERSON p
where p.id in (select p1.id from PERSON p1 where p1.name = "Joe")
or p.id in (select p2.id from PERSON p2
join CHILDREN c on p2.id = c.parent where c.name="Joe") \G
*************************** 1. row ***************************
id: 1
select_type: PRIMARY
table: a
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 247554
Extra: Using where
*************************** 2. row ***************************
id: 3
select_type: DEPENDENT SUBQUERY
table: NULL
type: NULL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: NULL
Extra: Impossible WHERE noticed after reading const tables
*************************** 3. row ***************************
id: 2
select_type: DEPENDENT SUBQUERY
table: a1
type: unique_subquery
possible_keys: PRIMARY,name,sortname
key: PRIMARY
key_len: 4
ref: func
rows: 1
Extra: Using where
3 rows in set (0.00 sec)

最重要的是,1. row 不使用任何索引并考虑 200k+ 行。坏的!此查询的执行耗时 0.7 秒,其中两个子查询都以毫秒为单位。

关于java - Hibernate Union 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/201023/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com