【问题标题】:JPA - query parameter is nullJPA - 查询参数为空
【发布时间】:2018-05-08 00:45:09
【问题描述】:
@Query("select users from User users  " +
        "where users.id like concat('%',?1,'%') and " +
        "users.name like concat('%',?2,'%') and " +
        "users.telNo like concat('%',?3,'%') ")
List<User> fuzzyQueryUser(Integer id, String name, String telNo);

当第一个参数id为空时,模糊查询无结果。如果数据库中有类似的条目,我希望在参数为 null 时得到结果。我该怎么办?谢谢你。

@Query("select users from User users  " +
    "where (users.id like concat('%',?1,'%') or ?1 is null or ?1 ='')and " +
    "(users.name like concat('%',?2,'%') or ?2 is null or ?2 ='') and " +
    "(users.telNo like concat('%',?3,'%') or ?3 is null or ?3 ='')")
List<User> fuzzyQueryUser(String id, String name, String telNo);

喜欢这个

@Query("select users from User users  " +
        "where (users.id like concat('%',?1,'%') or ?1 is null  )and " +
        "(users.name like concat('%',?2,'%') or ?2 is null or ?2 ='') and " +
        "(users.telNo like concat('%',?3,'%') or ?3 is null or ?3 ='')")
List<User> fuzzyQueryUser(Integer id, String name, String telNo);                        

【问题讨论】:

    标签: java spring jpa spring-data-jpa hql


    【解决方案1】:

    只需添加另一个条件即可忽略 null 和可选的空字符串:

    @Query("select users from User users  " +
            "where (users.id like concat('%',?1,'%') or ?1 is null) and " 
           +"users.name like concat('%',?2,'%') and " +
            "users.telNo like concat('%',?3,'%') ")
    

    【讨论】:

    • 太棒了!看看我的代码。这样,我就可以使用三个条件进行模糊查询,当一个条件为空时,这个条件的结果就是所有的值。
    • 但是'id''必须修改为String,而不是Integer,否则会出错
    • 哦!删除'或?1 ='''。这个可以用Integer,非常感谢。
    • 是的..在这种情况下最后一个或无关紧要..与另一个字符串参数错误。
    猜你喜欢
    • 2019-05-30
    • 2020-05-31
    • 2019-07-20
    • 2021-09-15
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    相关资源
    最近更新 更多