问题描述
我认为我永远不会完全理解获取连接.
I don't think I will ever fully understand fetch joins.
我有一个查询,我试图急切地将引用膨胀"到两个级别.
I have a query where I'm attempting to eagerly "inflate" references down two levels.
也就是说,我的 A
有一个可选的 Collection
的 B
,每个 B
要么有 0或 1 个 C
.已知 B
集合的大小很小(10-20 个顶部).我想预取这个图表.
That is, my A
has an optional Collection
of B
s, and each B
has either 0 or 1 C
. The size of the B
collection is known to be small (10-20 tops). I'd like to prefetch this graph.
A
的 B
关系被标记为 FetchType.LAZY
并且是可选的.B
与 C
的关系也是可选的,FetchType.LAZY
.
A
's B
relationship is marked as FetchType.LAZY
and is optional. B
's relationship to C
is also optional and FetchType.LAZY
.
我希望我能做到:
SELECT a
FROM A a
LEFT JOIN FETCH a.bs // look, no alias; JPQL forbids it
LEFT JOIN a.bs b // "repeated" join necessary since you can't alias fetch joins
LEFT JOIN FETCH b.c // this doesn't seem to do anything
WHERE a.id = :id
当我运行它时,我看到 A
的 B
集合确实被获取了(我在 SQL 中看到一个 LEFT JOIN
引用了B
映射到的表).
When I run this, I see that A
s B
collection is indeed fetched (I see a LEFT JOIN
in the SQL referencing the table to which B
is mapped).
但是,我没有看到任何证据表明 C
的表被获取.
However, I see no such evidence that C
's table is fetched.
如何从给定的 预取所有
?我看不出有什么办法可以做到这一点.C
和所有 B
和所有 C
的可达"一个
How can I prefetch all C
s and all B
s and all C
s that are "reachable" from a given A
? I can't see any way to do this.
推荐答案
JPA 规范不允许为 fetch join 设置别名,但一些 JPA 提供程序允许.
The JPA spec does not allow aliasing a fetch join, but some JPA providers do.
EclipseLink 从 2.4 开始执行.EclipseLink 还允许使用点符号(即JOIN FETCH a.bs.c")进行嵌套连接获取,并支持允许嵌套连接的查询提示eclipselink.join-fetch"(您可以指定多个提示相同的提示名称).
EclipseLink does as of 2.4. EclipseLink also allow nested join fetch using the dot notation (i.e. "JOIN FETCH a.bs.c"), and supports a query hint "eclipselink.join-fetch" that allows nested joins (you can specify multiple hints of the same hint name).
一般来说,在获取连接上使用别名时需要小心,因为您可能会影响返回的数据.
In general you need to be careful when using an alias on a fetch join, as you can affect the data that is returned.
看,http://java-persistence-performance.blogspot.com/2012/04/objects-vs-data-and-filtering-join.html
这篇关于我如何做一个“深"在 JPQL 中获取连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!