JPA多条件查询时 部分条件为空

1、使用@Query

public interface UserRepository extends JpaRepository<User,Long> {

    //字符串类型在 mysql 为 null 时,为 '' 字符串,如果为空,就使用 1 = 1 条件去查询
    @Query(value = "select * from people where if(?1 !='',name like concat('%',?1,'%'),1=1) and if(?2 !='',sex=?2,1=1)"+
    " and if(IFNULL(?3,'') !='',age=?3,1=1) and if(IFNULL(?4,'') !='',num=?4,1=1) ",nativeQuery = true)
    List<People> find(String name,String sex,Integer age,Integer num);
}

Tips:

  1. nativeQuery = true 的含义是使用原生 SQL,即注解中的 SQL 语句会生效,false 的话就不会生效。
  2. SQL语句中 ?1?2?3?4 的意思是代表方法中的第几个参数。
  3. SQL中模糊查询的写法为 like concat('%', ?1, '%')
  4. if(?1 !='',name like concat('%',?1,'%'),1=1) 代表传入的参数 name 如果不为 ""Spring 类型空是 "" 而不是 null )将参数传入 name ,如果为空时显示 1 = 1 代表参数为真,对查询结果不产生作用。IF 的语法满足 mysql 的基本语法,IF(expr1,expr2,expr3) , 如果 expr1 为真 (expr1 <> 0 以及 expr1 <> NULL) ,那么 IF() 返回 expr2 ,否则返回 expr3
  5. if(IFNULL(?3,'') !='',age=?3,1=1) 表示如果传入的年龄是 null ,则替换成空字符串,然后判断是否为空,不为空则将参数传入 age ,否则忽略不对查询结果产生影响。IFNULLmysql 中的一个函数,这个函数一般用来替换 NULL 值的。IFNULL(value1,value2),判断 value1 是否为 null,如果为 null 则用 value2 替换
  6. 参数定义时,定义数值,应使用 Integer,如果用 int 定义,当入参为 NULL 时,程序会报空指针错误。原因是 JAVAint 是值类型,非对象,不可以设置为 NULLinteger 是对象类型,可以设置为 NULL

2、使用Specification

@Override
  public Specification<ProjectRiskSituation> findSpec(){
    return (Root<ProjectRiskSituation> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) -> {
      List<Predicate> listPredicate = new ArrayList<>();

      try {
        if(null != this.getStartFallDate() && !"".equals(this.getStartFallDate())){
          Predicate p1 = criteriaBuilder.greaterThanOrEqualTo(root.get("fallDate"),this.getStartFallDate().split(" ")[0]);
          listPredicate.add(p1);
        }

        if(null != this.getEndFallDate() && !"".equals(this.getEndFallDate())){
          Predicate p2 = criteriaBuilder.lessThanOrEqualTo(root.get("fallDate"),this.getEndFallDate().split(" ")[0]);
          listPredicate.add(p2);
        }
         }catch (Exception e) {
        e.printStackTrace();
      }
      
       return criteriaBuilder.and(listPredicate.toArray(new Predicate[0]));
       // 或  return query.where(listPredicate.toArray(new Predicate[0])).getRestriction();
    };
  }
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值