【问题标题】:Select Query not working in NULL parameters JPA选择查询在 NULL 参数 JPA 中不起作用
【发布时间】:2022-12-18 11:58:06
【问题描述】:

我正在使用 spring-data-jpa 这是我的查询


    @Query(value = "select ea.* from employee ea where ids in (?1) and (?2 is null or country=?2) ", nativeQuery = true)
    Page<Employee> findByds(List<UUID> ids,String country ,Pageable pageable );

我只想在参数country 不为空时通过匹配国家/地区获取员工列表,否则我想获取iDs 中的所有记录

SQL 查询在国家/地区参数为空的情况下不起作用。我希望我的查询像

  1. 当国家为空时select ea.* from employee ea where ids in (?1)

  2. 当国家不为空时select ea.* from employee ea where ids in (?1) and country =?2

【问题讨论】:

  • 将 (?2 is null or country=?2) 更改为 (country is null or country=?2)
  • (country is null or country=?2) 仅返回具有 null 值的记录

标签: java sql spring postgresql spring-boot


【解决方案1】:
You can use Case when Condition 

select 
    case when 
        ea.country is null then 
            (select ea.* from employee ea where ids in (?1))
        when 
       ea.country = ?2 then 
            (select ea.* from employee ea where ids in (?1) and country =?2 )
      end
from employee ea      

【讨论】:

    【解决方案2】:

    为什么要使用本机查询? 这段代码对我有用。

    @Query("select p from Person p where p.id in (?1) and (?2 is null or p.country = ?2)")
    List<Person> find(List<Long> ids, String country);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 2014-01-19
      相关资源
      最近更新 更多