JPA - 查询参数为null

时间:2017-11-24 03:18:50

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

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

1 个答案:

答案 0 :(得分:3)

只需添加另一个条件即可忽略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,'%') ")