22 Specifications动态查询

Specifications动态查询

有时我们在查询某个实体的时候,给定的条件是不固定的,这时就需要动态构建相应的查询语句,在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);
}

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

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

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

使用Specifications完成条件查询

//依赖注入customerDao
    @Autowired
    private CustomerDao customerDao;
    @Test
    public void testSpecifications() {
          //使用匿名内部类的方式,创建一个Specification的实现类,并实现toPredicate方法
        Specification <Customer> spec = new Specification<Customer>() {
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //cb:构建查询,添加查询方式   like:模糊匹配
                //root:从实体Customer对象中按照custName属性进行查询
                return cb.like(root.get("cName").as(String.class), "张%");
            }
        };
        Customer customer = customerDao.findOne(spec);
        System.out.println(customer);
    }

方法对应关系

方法名称 Sql对应关系
equle filed = value
gt(greaterThan ) filed > value
lt(lessThan ) filed < value
ge(greaterThanOrEqualTo ) filed >= value
le( lessThanOrEqualTo) filed <= value
notEqule filed != value
like filed like value
notLike filed not like value
   

基于Specifications的分页查询

@Test
    public void testPage() {
        //构造查询条件
        Specification<Customer> spec = new Specification<Customer>() {
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                return cb.like(root.get("custName").as(String.class), "张%");
            }
        };

        /**
         * 构造分页参数
         *         Pageable : 接口
         *             PageRequest实现了Pageable接口,调用构造方法的形式构造
         *                 第一个参数:页码(从0开始)
         *                 第二个参数:每页查询条数
         */
        Pageable pageable = new PageRequest(0, 5);

        /**
         * 分页查询,封装为Spring Data Jpa 内部的page bean
         *         此重载的findAll方法为分页方法需要两个参数
         *             第一个参数:查询条件Specification
         *             第二个参数:分页参数
         */
        Page<Customer> page = customerDao.findAll(spec,pageable);

    }

对于Spring Data JPA中的分页查询,是其内部自动实现的封装过程,返回的是一个Spring Data JPA提供的pageBean对象。

  

原文地址:https://www.cnblogs.com/zhaochengf/p/12127850.html

时间: 2024-08-02 02:38:18

22 Specifications动态查询的相关文章

Spring Data JPA 的 Specifications动态查询

主要的结构: 有时我们在查询某个实体的时候,给定的条件是不固定的,这时就需要动态构建相应的查询语句,在Spring Data JPA中可以通过JpaSpecificationExecutor接口查询.相比JPQL,其优势是类型安全,更加的面向对象. import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import o

Linq 动态查询排序

Linq的排序一般是这样写的: query.OrderBy(x => x.Tel).Skip(0).Take(10); 实际使用中排序字段可能是通过字符类型的参数来设置的,于是想这样实现: query.OrderBy(x=>x.GetType().GetField("Tel")).Skip(0).Take(10); 上面的写法是无法编译通过的,此路不通,于是找到一个order扩展类: 1 using System; 2 using System.Linq; 3 using

T-SQL动态查询(4)——动态SQL

接上文:T-SQL动态查询(3)--静态SQL 前言: 前面说了很多关于动态查询的内容,本文将介绍使用动态SQL解决动态查询的一些方法. 为什么使用动态SQL: 在很多项目中,动态SQL被广泛使用甚至滥用,很多时候,动态SQL又确实是解决很多需求的首选方法.但是如果不合理地使用,会导致性能问题及无法维护.动态SQL尤其自己的优缺点,是否使用需要进行评估分析: 动态SQL优点: 动态SQL提供了强大的扩展功能,能够应付复杂的需求,即使在需求增加时也能应对,并且不会因为需求的增加而导致代码的线性增长

linq之InnerJoin和LeftJoin以及封装动态查询条件版本

Linq的出现,使数据集的处理显得愈来愈简便.很多时候对于本地数据集的处理,脑海中的第一反应,即尝试使用Linq来实现.诸如DataTable的innerJoin以及leftJoin等操作,很多时候我们一接到类似的需求,立马便动手,诸如以下demo: 一.InnerJoin 1 var qMyMx = from mxDr in _dtJgTcDetail.Rows.Cast<DataRow>().Where(drMx => id.Equals(drMx["TCID"]

Linq to Sql:N层应用中的查询(下) : 根据条件进行动态查询

原文:Linq to Sql:N层应用中的查询(下) : 根据条件进行动态查询 如果允许在UI层直接访问Linq to Sql的DataContext,可以省去很多问题,譬如在处理多表join的时候,我们使用var来定义L2S查询,让编译器自动推断变量的具体类型(IQueryable<匿名类型>),并提供友好的智能提示:而且可以充分应用L2S的延迟加载特性,来进行动态查询.但如果我们希望将业务逻辑放在一个独立的层中(譬如封装在远程的WCF应用中),又希望在逻辑层应用Linq to sql,则情

Linq to Sql : 动态构造Expression进行动态查询

原文:Linq to Sql : 动态构造Expression进行动态查询 前一篇在介绍动态查询时,提到一个问题:如何根据用户的输入条件,动态构造这个过滤条件表达式呢?Expression<Func<ProductExt, bool>> predicate t => t.ProductName.Contains("che") && t.UnitPrice >= 22; 理想情况下,我希望可以像下面这样来构造predicate,这样,我

SpringBoot动态查询 Specification使用

有时候需要用到动态查询.动态查询 Specification  使用需实现接口JpaSpecificationExecutor 1 package com.hik.dao; 2 3 import java.util.List; 4 5 import org.springframework.data.jpa.repository.JpaRepository; 6 import org.springframework.data.jpa.repository.JpaSpecificationExecu

Hibernate与Jpa的关系,以及使用分页和动态查询

最近由于项目调动,我去了使用JPA的项目组, 因为之前的项目组使用MyBatis,所以一时间关于JPA和Hibernate的知识体系记得不熟,导致出现了混乱:在网上看到了这篇文章,终于解决了我心中的疑惑:JPA是一种规范,Hibernate实现了这种规范 . 这篇短小精悍的文章给了我很多的启发,于是,我把它"复制"到了本文! http://blog.sina.com.cn/s/blog_5f1619e80100yoxz.html 我知道Jpa是一种规范,而Hibernate是它的一种实

flask_sqlalchemy获取动态 model名称 和 动态查询

需求 想要实现动态的查询,表名,字段,字段值都不是固定的 1 obj=表名.query.filter_by(字段=值1).first() 2 3 obj.字段=值2 首先动态获取db_model名字 1 class Role(db.Model): 2 __tablename__ = 'roles' 3 id = db.Column(db.Integer, primary_key=True) 4 name = db.Column(db.String(64)) 5 email=db.Column(d