一篇文章带你搞定 SpringDataJpa 中的 Specifications 动态查询

一、JpaSpecificationExecutor 接口

有时我们在查询某个实体的时候,给定的条件是不固定的,这时就需要动态构建相应的查询语句,在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);
   	//根据条件分页查询
   	//pageable:分页参数
	//返回值:分页 pageBean(page:是springdatajpa提供的)
 	Page<T> findAll(Specification<T> spec, Pageable pageable);
   	//排序查询查询
   	//Sort:排序参数
 	List<T> findAll(Specification<T> spec, Sort sort);
   	//统计查询
 	long count(Specification<T> spec);
}

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

Specification接口中只定义了如下一个方法:

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

二、使用 Specifications 完成条件查询

关于实体类和Dao 层接口的配置可参考:一篇文章带你快速入门 Spring Data JPA

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.yolo.jpa.domain.Customer;

import java.util.List;

/**
 * 符合SpringDataJpa的dao层接口规范
 *      JpaRepository<操作的实体类类型,实体类中主键属性的类型>
 *          * 封装了基本CRUD操作
 *      JpaSpecificationExecutor<操作的实体类类型>
 *          * 封装了复杂查询(分页)
 */
public interface CustomerDao extends JpaRepository<Customer,Long> ,JpaSpecificationExecutor<Customer> {

}

1. 根据条件查询单个对象

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

在这里插入图片描述

2. 多条件查询

 @Test
    public void testSpec() {
        /**
         *  root:获取属性
         *      客户名
         *      所属行业
         *  cb:构造查询
         *      1.构造客户名的精准匹配查询
         *      2.构造所属行业的精准匹配查询
         *      3.将以上两个查询联系起来
         */
        Specification<Customer> spec = new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<Object> custName = root.get("custName");//客户名
                Path<Object> custIndustry = root.get("custIndustry");//所属行业

                //构造查询
                //1.构造客户名的精准匹配查询
                Predicate p1 = cb.equal(custName, "Yolo_1");//第一个参数,path(属性),第二个参数,属性的取值
                //2..构造所属行业的精准匹配查询
                Predicate p2 = cb.equal(custIndustry, "yolo_1");
                //3.将多个查询条件组合到一起:组合(满足条件一并且满足条件二:与关系,满足条件一或满足条件二即可:或关系)
                Predicate and = cb.and(p1, p2);//以与的形式拼接多个查询条件
                // cb.or();//以或的形式拼接多个查询条件
                return and;
            }
        };
        Customer customer = customerDao.findOne(spec);
        System.out.println(customer);
    }

在这里插入图片描述

3. 模糊排序查询

  /**
     * 案例:完成根据客户名称的模糊匹配,返回客户列表
     *      客户名称以 ’Yolo_1‘ 开头
     *
     * equal :直接得到path对象(属性),然后进行比较即可
     * gt,lt,ge,le,like : 得到path对象,根据path指定比较的参数类型,再去进行比较
     *      指定参数类型:path.as(类型的字节码对象)
     */
    @Test
    public void testSpec() {
        //构造查询条件
        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), "Yolo%");
                return like;
            }
        };
        //List<Customer> list = customerDao.findAll(spec);
        //for (Customer customer : list) {
        //    System.out.println(customer);
        //}
        //添加排序
        //创建排序对象,需要调用构造方法实例化sort对象
        //第一个参数:排序的顺序(倒序,正序)
        //   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);
        }
    }

在这里插入图片描述

三、基于Specifications 的分页查询

1. 没有条件的分页查询

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

在这里插入图片描述

2. 有条件的分页查询

 分页查询
     * Specification: 查询条件
     * Pageable:分页参数
     	* 分页参数:查询的页码,每页查询的条数
     	* findAll(Specification,Pageable):带有条件的分页
     	* findAll(Pageable):没有条件的分页
     *  返回:Page(springDataJpa为我们封装好的pageBean对象,数据列表,共条数)
	 @Test
    public void testSpec() {
        
        Specification<Customer> spec = new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<Object> custName = root.get("custName");
                Predicate like = criteriaBuilder.like(custName.as(String.class), "Yolo%");
                return like;
            }
        };

        Pageable pageable = new PageRequest(0, 2);
        //分页查询
        Page<Customer> page = customerDao.findAll(spec, pageable);
        System.out.println("数据集合列表: " + page.getContent());
        System.out.println("总条数: " + page.getTotalElements());
        System.out.println("总页数:" + page.getTotalPages());
    }

在这里插入图片描述

四、使用 Specification 多表查询

 /**
     * Specification的多表查询
     */
    @Test
    public void testFind() {
        Specification<LinkMan> spec = new Specification<LinkMan>() {
            public Predicate toPredicate(Root<LinkMan> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //Join代表链接查询,通过root对象获取
                //创建的过程中,第一个参数为关联对象的属性名称,第二个参数为连接查询的方式(left,inner,right)
                //JoinType.LEFT : 左外连接,JoinType.INNER:内连接,JoinType.RIGHT:右外连接
                Join<LinkMan, Customer> join = root.join("customer", JoinType.INNER);
                Path<Object> custName = join.get("custName");
                return cb.like(custName.as(String.class), "yolo");
            }
        };
        List<LinkMan> list = linkManDao.findAll(spec);
        for (LinkMan linkMan : list) {
            System.out.println(linkMan);
        }
    }

在这里插入图片描述

五、方法对应关系的补充

方法名称Sql对应关系
equlefiled = value
gt(greaterThan )filed > value
lt(lessThan )filed < value
ge(greaterThanOrEqualTo )filed >= value
le( lessThanOrEqualTo)filed <= value
notEqulefiled != value
likefiled like value
notLikefiled not like value
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要使用 JPASpecifications 删除数据,首先需要创建一个符合要求的 Predicate 对象,然后将其传递给 delete 方法。下面是一个示例: ```java import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaDelete; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> { } public class UserRepositoryImpl implements UserRepositoryCustom { private final EntityManager entityManager; public UserRepositoryImpl(EntityManager entityManager) { this.entityManager = entityManager; } @Override public void deleteUsersByCondition(Specification<User> spec) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaDelete<User> delete = builder.createCriteriaDelete(User.class); Root<User> root = delete.from(User.class); Predicate predicate = spec.toPredicate(root, delete, builder); if (predicate != null) { delete.where(predicate); } entityManager.createQuery(delete).executeUpdate(); } } ``` 通过上述代码,你可以在 UserRepository 接口定义一个自定义方法 `deleteUsersByCondition`,并在 `UserRepositoryImpl` 类实现该方法。该方法接受一个 `Specification<User>` 对象作为参数,并将其转换为 `Predicate` 对象,然后使用 `CriteriaDelete` 对象去删除满足条件的数据。 使用时,你可以在你的代码调用 `deleteUsersByCondition` 方法,并传递适当的 `Specification<User>` 对象来指定删除条件。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南淮北安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值