【问题标题】:Jpql join on multipleJpql加入多个
【发布时间】:2017-06-20 21:46:58
【问题描述】:

我们有 2 个实体:A 和 B。

一个列表上有一个@OneToMany。

两个实体都有一个日期。

我们想要获取日期设置为空的 A 实体,并用日期设置为空的 B 填充它。

@Query("select a from A a " +
    "left join a.bs b " +
    "on b.date is null " +
    "where a.date is null")

我们想使用join是因为下面的请求,如果没有B,即使A有日期也不会显示A。

@Query("select a from A a where a.date is null and a.bs.date is null").

这里是用一个例子来解释的数据集

A              B1              B2              Result
date not set   Date not set    Date not set    no result
date not set   Date not set    Date set        no result
date not set   Date set        Date not set    no result
date not set   Date set        Date set        no result

date set       Date not set    Date not set    A only
date set       Date set        Date not set    A with B1
date set       Date not set    Date set        A with B2
date set       Date set        Date set        A with B1 + B2

示例类:

public class A {
    @Id
    private Long id;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "bId")
    private List<B> bs;
}


public class B {
    @Id
    private Long id;
}

非常感谢! :)

【问题讨论】:

    标签: java hibernate join jpql


    【解决方案1】:

    第二个查询应该是:

    @Query("select a from A a where a.date is null and a.bs.date is null").
    

    但这很奇怪,您的示例与您的查询不对应... 我会写这样的:

    @Query("select a from A where a.date is not null and a.bs.date is not null")
    

    【讨论】:

    • 嗨,谢谢你的回应,你对请求的权利,我编辑它,但是对于你的回应,如果 a.bs.date 为空且 a.date 不为空,那么会有没有结果。但是我们需要一个空 A 的结果。换句话说,我想要 JPQL 中的这个 SQL 查询:SELECT * FROM A a LEFT JOIN B b ON b.aId = a.id and b.date is null where a.date is空。
    猜你喜欢
    • 2013-12-21
    • 2013-06-17
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 2021-08-18
    • 2011-09-17
    • 2011-04-13
    • 2012-04-12
    相关资源
    最近更新 更多