本文主要是介绍springDataJpa多条件动态查询之JpaSpecificationExecutor,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在spring中多条件动态查询:
准备实体表:
多条件查询,加上排序
/*** 排序加上查询* 模糊查询 用户名 和 密码 和 状态*/@Testpublic void testQuery(){Specification<Student> specification = new Specification<Student>() {@Overridepublic Predicate toPredicate(Root<Student> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {// 1.root获取比较属性Path<String> username = root.get("username");Path<String> password = root.get("password");Path<Boolean> isDel = root.get("isDel");// 2.criteriaBuilder构造查询条件Predicate like = criteriaBuilder.like(username, "%用户名%");Predicate like1 = criteriaBuilder.like(password, "%码%");Predicate equal = criteriaBuilder.equal(isDel, false);// 级联条件,可以用 and 或者 orPredicate and = criteriaBuilder.and(like, like1, equal);// 返回查询条件return and;}};// 新建排序条件,按照成绩这一字段 降序排列Sort sort = new Sort(Sort.Direction.DESC,"grade");// 调用查询方法。把拼接的条件传入List<Student> all = studentRepository.findAll(specification,sort);for (Student student : all) {System.out.println(student);}}
结果:
多条件查询,分页加排序
/**** 多条件查询,在多个查询满足 用户名和多个成绩的数据* 分页加上排序*/@Testpublic void queryTest(){List<Integer> list = new ArrayList<>();list.add(1);list.add(2);list.add(3);list.add(4);Specification<Student> specification = new Specification<Student>() {@Overridepublic Predicate toPredicate(Root<Student> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {Path<String> username = root.get("username");Path<Integer> grade = root.get("grade");Predicate like = criteriaBuilder.like(username, "%名%");CriteriaBuilder.In<Integer> in = criteriaBuilder.in(grade);CriteriaBuilder.In<Integer> value=null;for (Integer integer : list) {value = in.value(integer);}// 拼接条件返回return criteriaBuilder.and(like, value);}};// 创建排序条件Sort sort = new Sort(Sort.Direction.DESC, "grade");// 创建分页条件 page为当前页 size为每页显示条数Pageable pageRequest = new PageRequest(1-1,10,sort);// 将条件和分页传入,返回pagePage<Student> all = studentRepository.findAll(specification, pageRequest);// 获得查询的数据List<Student> content = all.getContent();for (Student student : content) {System.out.println(student);}System.out.println("总数据数量:"+all.getTotalElements());System.out.println("总页数:"+all.getTotalPages());System.out.println("当前页:"+all.getNumber());System.out.println("当前页显示元素:"+all.getNumberOfElements());System.out.println(all.getPageable());System.out.println("每页显示个数:"+all.getSize());System.out.println("排序规则:"+all.getSort());}
查询结果
这篇关于springDataJpa多条件动态查询之JpaSpecificationExecutor的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!