Java 对JPQL的条件左外部联接SQL查询

Java 对JPQL的条件左外部联接SQL查询,java,sql,database,hibernate,jpql,Java,Sql,Database,Hibernate,Jpql,以下SQL查询的jpql等价物是什么: 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 |ac

以下SQL查询的jpql等价物是什么:

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

由于
@manytone
关系,自动添加条件
App.id=App\u Child.id
。在JPA2.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;

例如,请参阅。

如果您希望SQL查询查找所有具有“活动”应用程序子级的应用程序,您可以尝试使用exists而不是join

-- 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_子行,但只显示了“active”子行。此exists方法将适用于第一个查询,您只想检索应用程序,但如果您想同时获取应用程序和子应用程序,则它不会有任何帮助

不过,您可以向应用程序实体添加一个方法,以获取活动应用程序子对象的集合并映射适当的属性。您可以使用此“存在”查询获取所需的应用程序,然后在每个应用程序上调用getActiveChildren

我在你的小提琴上测试了SQL,下面是编辑:

此引用显示您存在于JPQL中。


希望这些信息足以让您试用。

JPA2.0中是否有类似于ON的内容?不幸的是,我不知道。一旦我们需要这个功能,我们就求助于本机查询。你能用子查询而不是连接来实现吗?JPQL允许子查询,我过去也曾将此作为一种变通方法。你能发布子查询变通方法吗?我发布了变通方法。我很想知道这是否有用?