如何正确表达JPQL“join fetch”用“where”条款为JPA 2 CriteriaQuery? [英] How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

查看:105
本文介绍了如何正确表达JPQL“join fetch”用“where”条款为JPA 2 CriteriaQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下JPQL查询:

Consider the following JPQL query:

SELECT foo FROM Foo foo
INNER JOIN FETCH foo.bar bar
WHERE bar.baz = :baz

我正在尝试将此转换为Critieria查询。这是我得到的:

I'm trying to translate this into a Critieria query. This is as far as I have gotten:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Foo> cq = cb.createQuery(Foo.class);
Root<Foo> r = cq.from(Foo.class);
Fetch<Foo, Bar> fetch = r.fetch(Foo_.bar, JoinType.INNER);
Join<Foo, Bar> join = r.join(Foo_.bar, JoinType.INNER);
cq.where(cb.equal(join.get(Bar_.baz), value);

这里显而易见的问题是我正在进行两次相同的连接,因为 Fetch< Foo,Bar> 似乎没有获得<$的方法c $ c>路径。
有没有办法避免必须加入两次?或者我是否必须坚持使用旧的JPQL并使用简单的查询?

The obvious problem here is that I am doing the same join twice, because Fetch<Foo, Bar> doesn't seem to have a method to get a Path. Is there any way to avoid having to join twice? Or do I have to stick with good old JPQL with a query as simple as that?

推荐答案

在JPQL中,规范中的情况也是如此.JPA规范不允许将别名赋予获取连接。通过限制连接提取的上下文,你可以轻松地用脚射击自己。连接两次更安全。

In JPQL the same is actually true in the spec. The JPA spec does not allow an alias to be given to a fetch join. The issue is that you can easily shoot yourself in the foot with this by restricting the context of the join fetch. It is safer to join twice.

这通常是一个问题ToMany比ToOnes。
例如,

This is normally more an issue with ToMany than ToOnes. For example,

Select e from Employee e 
join fetch e.phones p 
where p.areaCode = '613'

这将错误返回所有con的员工613区号中的数字,但会遗漏返回列表中其他区域的电话号码。这意味着拥有613和416区域代码电话的员工将丢失416电话号码,因此该对象将被破坏。

This will incorrectly return all Employees that contain numbers in the '613' area code but will left out phone numbers of other areas in the returned list. This means that an employee that had a phone in the 613 and 416 area codes will loose the 416 phone number, so the object will be corrupted.

当然,如果你知道的话你正在做什么,额外的连接是不可取的,一些JPA提供者可能允许别名连接提取,并可能允许将Criteria Fetch转换为Join。

Granted, if you know what you are doing, the extra join is not desirable, some JPA providers may allow aliasing the join fetch, and may allow casting the Criteria Fetch to a Join.

这篇关于如何正确表达JPQL“join fetch”用“where”条款为JPA 2 CriteriaQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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