如何在接受四种参数组合的 Spring Data Jpa 中编写选择查询 [英] How to write a select query in Spring Data Jpa that accepts four combinations of parameters

查看:30
本文介绍了如何在接受四种参数组合的 Spring Data Jpa 中编写选择查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在用户搜索多个组合时显示结果,他可以搜索的选项 -

<块引用>

  1. 国家
  2. 状态
  3. 邮政编码

他可以搜索的示例组合是 (country,state)、(country,district)、(state,zipCode) 等.

我也在使用 Spring Data Jpa 进行查询和分页.

我是 Spring Jpa 的新手,任何帮助将不胜感激.

谢谢!

解决方案

有一个非常简单的技巧可以执行您需要的操作 ;)

@Query("select e from Entity e where "+"(:country = '' 或 e.country like '%:country%') 和 "+"(:state = '' 或 e.state like '%:state%') 和 "+"(:district = '' or e.district like '%:district%') 和 "+"(:zipCode = '' or e.zipCode like '%:zipCode%')"页面<实体>高级搜索(@Param(国家")字符串国家,@Param("state") 字符串状态,@Param("district") 字符串区,@Param("zipCode") 字符串邮政编码,可分页页面);

所以当你需要调用advancedSearch时,你可以只设置你需要的参数,其他设置为"":

页面<实体>enityPages = advancedSearch("", "California", "1st", "", new PageRequest(...));

I am trying to display results when the user search for several combinations, the options he can search by -

  1. country
  2. state
  3. district
  4. zipCode

example combinations he can search are (country,state), (country,district), (state,zipCode) etc..

I am using Spring Data Jpa for my queries and pagination as well.

I am new to Spring Jpa, Any help will be appreciated.

Thank you!

解决方案

There is a very simple trick to perform what do you need ;)

@Query("select e from Entity e where "
      +"(:country = '' or e.country like '%:country%') and "
      +"(:state = '' or e.state like '%:state%') and "
      +"(:district = '' or e.district like '%:district%') and "
      +"(:zipCode = '' or e.zipCode like '%:zipCode%')"
Page<Entity> advancedSearch(@Param("country") String country,
                            @Param("state") String state,
                            @Param("district") String district,
                            @Param("zipCode") String zipCode,
                            Pageable page);

So when you need to invoke advancedSearch you can set parameters only you need and other set to "":

Page<Entity> enityPages = advancedSearch("", "California", "1st", "", new PageRequest(...)); 

这篇关于如何在接受四种参数组合的 Spring Data Jpa 中编写选择查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆