【问题标题】:JPQL query for parameter in listJPQL 查询列表中的参数
【发布时间】:2021-08-22 16:11:33
【问题描述】:

我有两个 JPA 实体:

public class BusinessTripRequest extends StandardEntity {
    @OneToMany(mappedBy = "businessTripRequest", fetch = FetchType.LAZY)
    @OnDelete(DeletePolicy.CASCADE)
    @Composition
    protected List<HotelBooking> hotelBookings;
}

public class HotelBooking extends StandardEntity {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "BUSINESS_TRIP_REQUEST_ID")
    protected BusinessTripRequest businessTripRequest;

    @Column(name = "JOINT_CHECK_IN")
    protected Boolean jointCheckIn;
}

我尝试编写一个 JPQL 查询来提取以下请求:

  • 如果参数为false,则提取所有带有空hotelBookings 的请求,并且每个预订都有参数jointCheckIn 的所有请求设置为false
  • 如果参数为true,则提取所有具有一个或多个预订的请求,jointCheckIn 设置为true

我写了这样的东西

从 nk$BusinessTripRequest 中选择 e 加入 e.hotelBookings hb
其中 (true = ? 并且 e.hotelBookings 不为空并且 hb.jointCheckIn = 真的)
或(false = ? 且 e.hotelBookings 为空)

由于第一个条件,参数为true时效果很好。但是我写不出false参数的工作条件

【问题讨论】:

  • 你能有 2 个查询并根据你的标志参数调用其中一个吗?
  • :1代替?怎么样?
  • @tremendous7 不幸的是,没有。该参数在过滤器中使用并被替换而不是问号。我只能更改此查询
  • @dan1st 在我正在使用的框架中,有一个问号而不是一个参数

标签: java jpa jpql


【解决方案1】:

cmets 建议的解决方案

select e
from nk$BusinessTripRequest e
where (true = ? and e.id in (select hb1.businessTripRequest.id
                         from HotelBooking hb1
                         where hb1.jointCheckIn = true))
   or (false = ? and {E}.id not in (select hb1.businessTripRequest.id
                                    from nokia$HotelBooking hb1
                                    where hb1.jointCheckIn = true))

【讨论】:

  • 结果是一样的:/
  • @АрсланХаликов 多哈。 select e from nk$BusinessTripRequest e left join e.hotelBookings hb where (true = ? and e.hotelBookings is not empty and hb.jointCheckIn = true) or (false = ? and hb is null) 呢?
  • @АрсланХаликов select e from nk$BusinessTripRequest e where (true = ? and e.id in (select hb1.businessTripRequest.id from HotelBooking hb1 where hb1.jointCheckIn = true)) or (false = ? and e.id not in (select hb1.businessTripRequest.id from HotelBooking hb1)) 呢?
  • 是的,它有效。但是在第二种情况下进行了小幅更正:(false = ? and {E}.id not in (select hb1.businessTripRequest.id from nokia$HotelBooking hb1 where hb1.jointCheckIn = true)) 请编辑您的答案或写一个新答案,我将其标记为解决方案。谢谢?
  • @АрсланХаликов 根据您的建议编辑了答案
猜你喜欢
  • 2016-04-01
  • 2018-10-18
  • 2014-10-18
  • 2018-08-15
  • 2013-02-03
  • 2016-03-29
  • 2018-11-07
  • 2013-11-16
  • 2018-09-04
相关资源
最近更新 更多