Specifications动态查询

Specifications动态查询

有时我们在查询某个实体的时候,给定的条件是不固定的,这时就需要动态构建相应的查询语句,在Spring Data JPA中可以通过JpaSpecificationExecutor接口查询。相比JPQL,其优势是类型安全,更加的面向对象。
JpaSpecificationExecutor中定义的方法

	//根据条件查询一个对象
 	T findOne(Specification<T> spec);	
   	//根据条件查询集合
 	List<T> findAll(Specification<T> spec);
   	//根据条件分页查询
 	Page<T> findAll(Specification<T> spec, Pageable pageable);
   	//排序查询查询
 	List<T> findAll(Specification<T> spec, Sort sort);
   	//统计查询
 	long count(Specification<T> spec);

Specification构造的就是查询条件

使用Specifications完成条件查询

查询单个
测试方法

 @Autowired
    private CustomerDao customerDao;

    /**
     * 动态查询
     * 查询单个对象,根据条件查询
     */
    @Test
    public void  testSpec(){
        //构建查询条件  匿名内部类
        /**
         * 自定义查询条件
         *      1.实现Specification接口(需要提供泛型:查询对象的类型)
         *      2.实现toPredicate方法(构造查询条件)
         *      3.需要借助方法参数中的两个参数(root:获取需要查询的对象属性
         *         CriteriaBuilder:构造查询条件,内部封装了很多的查询条件(模糊匹配,精准匹配))
         *  案例:根据客户名称查询,查询名为程序猿的客户
         *        查询条件:
         *            1.查询方式
         *              cb对象
         *            2.比较的属性名称
         *               root对象中
         */
        Specification<Customer> spec= new Specification<Customer>() {
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                //1.获取比较的属性
                Path<Object> custName = root.get("custName");
                //2.构造查询条件 equal:进行精准匹配
                /**
                 * 第一个参数:需要比较的属性(path对象)
                 * 第二个参数:当前需要比较的取值  程序猿
                 */
                Predicate equal = cb.equal(custName,"程序猿");//比较的属性,比较属性的取值
                return equal;
            }
        };
        Customer customer = customerDao.findOne(spec);
        System.out.println(customer);
    }

多条件查询


    /**
     * 多条件查询
     *    案例:根据用户名(传智播客)和客户所属行业查询(it教育)
     *
     */
    @Test
    public void testSpec1(){
        /**
         * root:获取属性
         *      1.客户名称
         *      2.所属行业
         * cb:构造查询
         *      1.构造客户名的精准匹配查询
         *      2.构造所属行业的精准匹配查询
         *      3.将以上两个查询联系起来
         */
        Specification<Customer> spec=new Specification<Customer>() {
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<Object> custName = root.get("custName");//客户名
                Path<Object> custIndustry = root.get("custIndustry");//所属行业
                //构造查询
                //1.构造客户名的精准匹配查询
                Predicate p1= criteriaBuilder.equal(custName, "p图");//第一个参数,path(属性),属性的取值
                //2.构造所属行业的精准匹配查询
                Predicate p2 = criteriaBuilder.equal(custIndustry, "多媒体");
                //3.将多个查询条件组合到一起:组合(满足条件一并且满足条件二:与关系 ,满足条件一或满足条件二即可: 或关系 )
                Predicate predicate = criteriaBuilder.and(p1, p2);//and方法以与的形式拼接多个查询条件
                //criteriaBuilder.or()  or方法以或的形式拼接多个查询条件
                return predicate;
            }
        };
        Customer customer = customerDao.findOne(spec);
        System.out.println(customer);
    }

模糊查询 分页

 /**
     * 需求:完成根据客户名称的模糊匹配,返回客户列表
     *    客户名称以 程序 开头
     *  equal:直接得到path对象(属性) 然后进行比较
     *  gt lt ge le like:得到path对象,根据path指定比较的参数类型,再去进行比较
     *    指定参数类型:path.as(属性的类型的字节码对象)
     */
    @Test
    public void testSpec3(){
        //1.构造查询条件
        Specification<Customer> spec=new Specification<Customer>() {
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //查询属性
                Path<Object> custName = root.get("custName");
                //查询方式:模糊匹配
                Predicate like = criteriaBuilder.like(custName.as(String.class), "程序%");
                return like;
            }
        };
//        List<Customer> list = customerDao.findAll(spec);
//        for (Customer customer:list){
//            System.out.println(customer);
//        }
        //添加排序
        //创建排序对象,需要调用构造方法实例化对象
        //第一个参数排序的顺序 (倒序,正序)
        //Sort.Direction.DESC倒序 Sort.Direction.ASC 升序
        //第二个参数 排序的属性名
        Sort sort=new Sort(Sort.Direction.DESC,"custId");
        List<Customer> list = customerDao.findAll(spec, sort);
        for (Customer customer:list){
            System.out.println(customer);
        }
    }

分页查询

 /**
     * 分页查询
     *    Specification:查询条件
     *    PageTable:分页参数
     *       参数 查询的页码,每页查询的条数
     *    findAll(Specification,Pageable):带有条件的分页
     *    findAll(Pageable):没有条件的分页
     *  返回 Page对象(springDataJpa为我们封装好的pageBean对象,数据列表,总条数)
     */
    @Test
    public void testSpec4(){
        Specification spec=null;
        //PageRequest是Pageable接口的实现类
        /**
         * 创建PageRequest的过程中 需要调用他的构造方法传入两个参数
         *   第一个参数:当前查询的页数(从0开始)
         *   第二个参数:每页查询的数量
         */
        Pageable pageable=new PageRequest(0,2);
        Page<Customer> page = customerDao.findAll(null, pageable);
        System.out.println(page.getContent());//得到数据集合列表
        System.out.println(page.getTotalPages());//得到总页数
        System.out.println(page.getTotalElements());//得到总条数
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值