【问题标题】:conditional left outer join SQL query To JPQL条件左外连接 SQL 查询到 JPQL
【发布时间】:2012-10-25 05:18:03
【问题描述】:

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

【问题讨论】:

  • 你能用子查询代替连接吗? JPQL 允许子查询,我过去曾将其用作解决方法。
  • 你能发布你的子查询解决方法吗?
  • 我发布了解决方法。我很想知道它是否有帮助?

标签: java sql database hibernate jpql


【解决方案1】:

由于@ManyToOne 关系,自动添加条件App.id=App_Child.id。在 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

【讨论】:

  • 在 jpa 2.0 中有什么相当于 ON 的吗?
  • 不幸的是,我不知道。一旦我们需要该功能,我们最终会求助于本机查询。
【解决方案2】:

如果您想要一个 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 中获取列,但仅显示“活动”子行,但在您的小提琴中。这个 exists 方法适用于您只想检索应用程序的第一个查询,但如果您想同时获取应用程序和子项,那么它将无济于事。

您可以做的是向 App 实体添加一个方法,以获取 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

希望这些信息足以让您尝试一下。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多