我如何进行“深层"处理?获取加入JPQL? [英] How do I do a "deep" fetch join in JPQL?

查看:92
本文介绍了我如何进行“深层"处理?获取加入JPQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我永远不会完全理解提取联接.

我有一个查询,我试图在其中热切地膨胀"两级参考.

也就是说,我的A有一个可选的Collection of B s,每个B都有0或1个C.已知B集合的大小很小(10-20个顶部).我想预取该图.

AB关系被标记为FetchType.LAZY,并且是可选的. BC的关系也是可选的,而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

运行此命令时,我发现确实提取了AB集合(我在SQL中看到了引用B映射到的表的LEFT JOIN).

但是,我看不到任何证据表明C的表已被提取.

如何从给定的A中预取所有可达"的所有C和所有B和所有C?我看不到任何办法.

解决方案

JPA规范不允许别名化获取连接,但某些JPA提供程序却允许.

EclipseLink从2.4开始. EclipseLink还允许使用点表示法(即"JOIN FETCH a.bs.c")来嵌套连接获取,并支持允许嵌套连接的查询提示"eclipselink.join-fetch"(您可以指定相同提示名称的多个提示) ).

通常,在访存联接上使用别名时,请务必小心,因为这可能会影响返回的数据.

看, http://java-persistence -performance.blogspot.com/2012/04/objects-vs-data-and-filtering-join.html

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.

That is, my A has an optional Collection of Bs, 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's B relationship is marked as FetchType.LAZY and is optional. B's relationship to C is also optional and FetchType.LAZY.

I was hoping I could do:

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

When I run this, I see that As B collection is indeed fetched (I see a LEFT JOIN in the SQL referencing the table to which B is mapped).

However, I see no such evidence that C's table is fetched.

How can I prefetch all Cs and all Bs and all Cs that are "reachable" from a given A? I can't see any way to do this.

解决方案

The JPA spec does not allow aliasing a fetch join, but some JPA providers do.

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.

See, http://java-persistence-performance.blogspot.com/2012/04/objects-vs-data-and-filtering-join.html

这篇关于我如何进行“深层"处理?获取加入JPQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆