JPA查询:如何过滤条件为null的查询条件

JPA查询:如何过滤条件为null的查询条件

问题:JPA不会自动过滤为null的查询条件;

解决方案:

方案一:调用JPA之前判断,写多个查询方法;

方案二:利用原生sql 加 if的方式实现参数为空不作为查询条件;

例如:

@Query(value = "select * from user where is_identification = 1 and is_inter_identification = 1  and if(?1 !='',mobile=?1,1=1) and if(?2 !='',nick=?2,1=1)",nativeQuery = true)
List<User> findBySearch(String mobile,String nick);

注意:if(?1 !='',x1=?1,1=1) 代表传入的参数X1如果不为""(Spring类型空是""而不是null)。

思考:传入值null,需要用""判断;如果是真的""空字符串,又如何判断呢?

还有其他更好的解决方案,望大神留言,感激!!!!

原文地址:https://www.cnblogs.com/lizm166/p/13451172.html