条件左外连接SQL查询到JPQL

时间:2012-11-05 11:15:12

标签: java sql database hibernate jpql

SQL FIDDLE LINK FOR THIS DATA

jpql 等同于以下 SQL 查询:

select * from App left outer join App_Child on (App.id=App_Child.id and App_Child.status = 'active') where App.status='active' and App.id=1;

示例数据:

ij> select * from App;
ID         |STATUS
----------------------
1          |active
2          |active1
3          |active3
5          |active

4 rows selected
ij> select * from App_Child;
ID         |STATUS    |D
----------------------------------
1          |active    |1
2          |active11  |2
1          |active111 |3
1          |active    |4

4 rows selected
ij> select * from App left outer join App_Child on (App.id=App_Child.id and App_Child.status = 'active') where App.status='active' and App.id=1;
ID         |STATUS    |ID         |STATUS    |D
---------------------------------------------------------
1          |active    |1          |active    |1
1          |active    |1          |active    |4

2 rows selected
ij> select * from App left outer join App_Child on (App.id=App_Child.id and App_Child.status = 'active') where App.status='active' and App.id=5;
ID         |STATUS    |ID         |STATUS    |D
---------------------------------------------------------
5          |active    |NULL       |NULL      |NULL

1 row selected

编辑:我们正在使用 jpa 2.0

2 个答案:

答案 0 :(得分:3)

由于App.id=App_Child.id关系,会自动添加条件@ManyToOne。在JPA 2.1中,您可以使用显式on子句添加其他条件:

select a 
from App a left outer join 
     a.children c on (c.status = 'active') 
where a.status='active' and a.id=1;

请参阅示例EclipseLink Documentation

答案 1 :(得分:0)

如果您希望SQL查询找到具有“活动”App_Child的所有应用程序,您可以尝试使用而不是加入。

-- Alternative SQL to join
select a.* from App a where a.ID = 1 and exists (select * from App_Child b where a.id=b.id AND b.STATUS = 'active')

在你的例子中,你有两件事情在继续。在此页面上的SQL示例中,您只是从App表中获取列。虽然你从App表中获取了列,但是只显示了“活动”子行的App_Child。这个存在方法适用于您只想要检索应用程序的第一个查询,但如果您想要同时获取应用程序和子项,那么它将无济于事。

您可以做的是向应用程序添加一个方法,以获取Active App_Child的集合并映射适当的属性。您可以使用此“存在”查询获取所需的应用程序,然后在每个应用程序上调用getActiveChildren。

我在你的小提琴上测试了SQL,这里是编辑:http://sqlfiddle.com/#!4/0f39a/6/2

此参考显示您存在于JPQL中。 http://openjpa.apache.org/builds/1.2.0/apache-openjpa-1.2.0/docs/manual/jpa_langref.html#jpa_langref_exists

希望你有足够的信息来试试。

相关问题