ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Specifications动态查询

2020-05-27 20:02:13  阅读:341  来源: 互联网

标签:Specifications cb Specification 查询 动态 root spec 属性


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

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;

/**
 *  JpaSpecificationExecutor中定义的方法
 **/
 public interface JpaSpecificationExecutor<T> {
    //根据条件查询一个对象
    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

对于JpaSpecificationExecutor,这个接口基本是围绕着Specification接口来定义的。我们可以简单的理解为,Specification构造的就是查询条件。
Specification接口中只定义了如下一个方法

//构造查询条件
    /**
    *   root    :Root接口,代表查询的根对象,可以通过root获取实体中的属性
    *   query   :代表一个顶层查询对象,用来自定义查询
    *   cb      :用来构建查询,此对象里有很多条件方法
    **/
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb);

用法

1、findOne

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

b、多条件拼接

d testSpec() {
        //匿名内部类
        /**
         * 自定义查询条件
         *      1.实现Specification接口(提供泛型:查询的对象类型)
         *      2.实现toPredicate方法(构造查询条件)
         *      3.需要借助方法参数中的两个参数(
         *          root:获取需要查询的对象属性
         *          CriteriaBuilder:构造查询条件的,内部封装了很多的查询条件(模糊匹配,精准匹配)
         *       )
         *  案例:根据客户名称查询,查询客户名为传智播客的客户
         *          查询条件
         *              1.查询方式
         *                  cb对象
         *              2.比较的属性名称
         *                  root对象
         *
         */
        Specification<Customer> spec = new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //1.获取比较的属性
                Path<Object> custId = root.get("custId");//查询的是属性名,不是表的字段名
                //2.构造查询条件  :    select * from cst_customer where cust_id = 3
                /**
                 * 第一个参数:需要比较的属性(path对象)
                 * 第二个参数:当前需要比较的取值
                 */
                Predicate predicate = cb.equal(custId, 3);//进行精准的匹配  (比较的属性,比较的属性的取值)
                return predicate;
            }
        };
        Optional<Customer> customer = customerDao.findOne(spec);
        System.out.println(customer.get());

模糊匹配

      • equal :直接的到path对象(属性),然后进行比较即可
      • gt,lt,ge,le,like : 得到path对象,根据path指定比较的参数类型,再去进行比较
        指定参数类型:path.as(类型的字节码对象)
public void testSpec3() {
        //构造查询条件
        Specification<Customer> spec = new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //查询属性:客户名
                Path<Object> custName = root.get("custName");
                //查询方式:模糊匹配
                Predicate like = cb.like(custName.as(String.class), "d%");
                return like;
            }
        };

        List<Customer> list = customerDao.findAll(spec);
        for (Customer customer : list) {
            System.out.println(customer);
        }
    }

排序

public void testSpec3() {
        //构造查询条件
        Specification<Customer> spec = new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //查询属性:客户名
                Path<Object> custName = root.get("custName");
                //查询方式:模糊匹配
                Predicate like = cb.like(custName.as(String.class), "d%");
                return like;
            }
        };

        Sort sort = new Sort(Sort.Direction.DESC,"custId");
        List<Customer> list = customerDao.findAll(spec, sort);
        for (Customer customer : list) {
            System.out.println(customer);
        }
    }

分页查询

创建PageRequest的过程中,需要调用他的构造方法传入两个参数

  • 第一个参数:当前查询的页数(从0开始)
  • 第二个参数:每页查询的数量
  • public void testSpec4() {
    
            Specification<Customer> spec = new Specification<Customer>() {
                @Override
                public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    //查询属性:客户名
                    Path<Object> custName = root.get("custName");
                    //查询方式:模糊匹配
                    Predicate like = cb.like(custName.as(String.class), "d%");
                    return like;
                }
            };
            //PageRequest对象是Pageable接口的实现类
    
            Pageable pageable = PageRequest.of(0,1);;
            //分页查询
            Page<Customer> page = customerDao.findAll(spec, pageable);
            System.out.println(page.getContent()); //得到数据集合列表
            System.out.println(page.getTotalElements());//得到总条数
            System.out.println(page.getTotalPages());//得到总页数
        }

    可参考:https://www.cnblogs.com/derry9005/p/6282571.html

     

标签:Specifications,cb,Specification,查询,动态,root,spec,属性
来源: https://www.cnblogs.com/zouhong/p/12976120.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有