Left join on unrelated tables in Query DSL and JPA

风格不统一 提交于 2019-12-24 03:39:39

问题


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. In SQL this is easy:

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:

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:

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.

Question is: how to join two unrelated tables using Query DSL and JPA and avoiding native SQL? Is it possible? Sorting and filtering on fields from tableA and tableB.name is a requirement.


回答1:


Join on unrelated entities is not covered by latest JPA spec (2.1)

However Hibernate 5.1.0+ and EclipseLink 2.4.0+ support ad hoc joins. http://blog.anthavio.net/2016/03/join-unrelated-entities-in-jpa.html



来源:https://stackoverflow.com/questions/27619030/left-join-on-unrelated-tables-in-query-dsl-and-jpa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!