spring 选择查询在空参数JPA中不起作用

jqjz2hbq  于 2022-12-10  发布在  Spring
关注(0)|答案(3)|浏览(162)

我使用的是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)
1.国家/地区不为空时select ea.* from employee ea where ids in (?1) and country =?2

slsn1g29

slsn1g291#

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
u5rb5r59

u5rb5r592#

为什么要使用原生查询?这段代码对我很有效。

@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);
yr9zkbsy

yr9zkbsy3#

this is spring-data use @query and spel
Evans发布系列的最新SpringDataJPAM1版本通过添加支持来缓解这种痛苦

您可以使用EntityManager

相关问题