[英]Left join on unrelated tables in Query DSL and JPA
I have two unrelated tables, each one with field email. 我有两个不相关的表,每个表都带有外地电子邮件。 I need a query which introduces column taken from second table if emails match or will be null if no match is found.
我需要一个查询,如果邮件匹配,该查询将从第二个表中获取列;如果找不到匹配项,则为null。 In SQL this is easy:
在SQL中,这很容易:
SELECT tableA.id, tableA.email, tableB.name
FROM tableA
LEFT JOIN tableB ON tableA.email=tableB.email
ORDER BY tableB.name
Unfortunately JPA doesn't allow joins over unrelated entities so I converted it to: 不幸的是,JPA不允许对不相关实体的联接,因此我将其转换为:
SELECT tableA.id, tableA.email,
(SELECT tableB.name FROM tableB WHERE tableB.email=tableA.email) AS aname
FROM tableA
ORDER BY aname
Now, it works as JPA query but we are using Query DSL so off we go to converting it: 现在,它可以用作JPA查询,但是我们使用的是Query DSL,因此我们开始转换它:
JPQLQuery query = new JPAQuery(em);
List<Dto> items=query.from(qTableA)
.list(new QDto(qTableA.id, qTableA.email,
new JPASubQuery().from(qTableB)
.where(qTableB.email.eq(qTableA.email)).unique(qTableB.name)))
It works but now I have no idea how to implement sorting and filtering by field introduced by subquery. 它有效,但是现在我不知道如何通过子查询引入的字段来实现排序和过滤。
Dto
is a POJO used to collect results, QDto
is a class autogenerated from Dto
. Dto
是用来收集结果的POJO, QDto
是自动生成的一类Dto
。
Question is: how to join two unrelated tables using Query DSL and JPA and avoiding native SQL? 问题是:如何使用查询DSL和JPA联接两个不相关的表并避免使用本机SQL? Is it possible?
可能吗? Sorting and filtering on fields from tableA and tableB.name is a requirement.
必须对tableA和tableB.name中的字段进行排序和过滤。
Join on unrelated entities is not covered by latest JPA spec (2.1) 最新JPA规范(2.1)不适用于无关实体的加入
However Hibernate 5.1.0+ and EclipseLink 2.4.0+ support ad hoc joins. 但是Hibernate 5.1.0+和EclipseLink 2.4.0+支持临时连接。 http://blog.anthavio.net/2016/03/join-unrelated-entities-in-jpa.html
http://blog.anthavio.net/2016/03/join-unrelated-entities-in-jpa.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.