【问题标题】:Spring Data JPA query with optional paramters带有可选参数的 Spring Data JPA 查询
【发布时间】:2018-08-16 07:57:35
【问题描述】:

我有一个 GET 端点,它根据以下参数获取数据。 firstName 是必需的,其余都是可选的。

{

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

}

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

findByFirstNameOrLastNameOrGenderOrCity(firstName,lastName,Gender,City)

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

【问题讨论】:

    标签: spring-data deltaspike-jpa


    【解决方案1】:

    如果你需要这样的东西:

    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) " +
        "and (?4 is null or e.city = ?4)")
    List<MyEntities> getByFilter(String firstName, String lastName, Boolean gender, String city);
    

    【讨论】:

    • @Cerp0 我已经尝试过这个查询,但它没有按预期返回结果,在我的情况下,当所有参数(包括可选参数)都被传递时,我将只有一条记录,但不知何故它正在null 值 --- 这就是它在控制台上打印的内容 bind => [male, male, null, null, null, null, firstNmae, firstNmae, lastName, lastName]
    • @VinayVullakula 对不起,我不明白你的意思)你能否提供一个详细的例子(在你的问题中)你需要实现什么?
    猜你喜欢
    • 1970-01-01
    • 2019-04-22
    • 2017-11-29
    • 2020-01-08
    • 2012-07-21
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    相关资源
    最近更新 更多