带有可选参数的 Spring Data JPA 查询 [英] Spring Data JPA query with optional paramters

查看:49
本文介绍了带有可选参数的 Spring Data JPA 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 GET 端点,它根据以下参数获取数据.firstName 是强制性的,其余都是可选的.

<代码>{"名字:"","姓氏:"","性别:"","城市"""}

我应该如何处理数据库查询?我正在使用 Sring 数据 JPA,我试过了

findByFirstNameOrLastNameOrGenderOrCity(firstName,lastName,Gender,City)

不确定使用 @Query 注释的本机 sql 查询是否可以工作,因为如果端点的使用者没有发送值,除了 firstName 之外的任何值都可以为 null.请帮忙

解决方案

如果您需要这样的东西:

GET/myEntities?firstName=bla-bla&lastName=bla-bla&gender=1&city=bla-bla

<块引用>

其中 firstName 是强制性的,其余都是可选的,

那么你可以像这样查询:

@Query("select e from MyEntity e where e.firstName = ?1 " +"and (?2 is null or e.lastName = ?2) " +"and (?3 is null or e.gender = ?3) " +和(?4 为空或 e.city = ?4)")列表<我的实体>getByFilter(String firstName, String lastName, 布尔性别, String city);

I have an GET endpoint which fetches the data based on the below parameters. firstName is mandatory and rest all are optional.

{

"firstName:"",
"lastName:"",
"Gender:"",
"city"""

}

How should i approach for the database query? i am using Sring Data JPA, I have tried

findByFirstNameOrLastNameOrGenderOrCity(firstName,lastName,Gender,City)

Not sure if a native sql query using @Query annotation will work as any of the values apart from firstName can be null if the consumer of the endpoint is not sending the values. Kindly help

解决方案

If you need something like this:

GET /myEntities?firstName=bla-bla&lastName=bla-bla&gender=1&city=bla-bla

where firstName is mandatory and rest all are optional,

then you can use like this query:

@Query("select e from MyEntity e where e.firstName = ?1 " +
    "and (?2 is null or e.lastName = ?2) " + 
    "and (?3 is null or e.gender = ?3) " +
    "and (?4 is null or e.city = ?4)")
List<MyEntities> getByFilter(String firstName, String lastName, Boolean gender, String city);

这篇关于带有可选参数的 Spring Data JPA 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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