Specifications动态查询
public interface JpaSpecificationExecutor<T> { Optional<T> findOne(@Nullable Specification<T> spec);//查询单个对象 List<T> findAll(@Nullable Specification<T> spec);//查询列表 //查询全部,分页 //pageable:分页参数 //返回值就是一个分页pagebean(page:是springdatajpa提供的) Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable); //查询列表 //sort:排序参数 List<T> findAll(@Nullable Specification<T> spec, Sort sort); //统计查询 long count(@Nullable Specification<T> spec); }
Specification:代表的就是查询条件
自定义我们自己的Specification实现类
实现
//Root:查询的根对象(查询的任何属性都可以从更对象获取)
CriteriaQuery:顶层查询对象,自定义查询方式(了解,一般不用)
CriteriaBuilder:查询构造器,封装了很多查询条件
/** * Creates a WHERE clause for a query of the referenced entity in form of a {@link Predicate} for the given * {@link Root} and {@link CriteriaQuery}. * * @param root must not be {@literal null}. * @param query must not be {@literal null}. * @param criteriaBuilder must not be {@literal null}. * @return a {@link Predicate}, may be {@literal null}. */ @Nullable Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder);
pom.xml
<properties> <spring.version>5.2.14.RELEASE</spring.version> <hibernate.version>5.0.7.Final</hibernate.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <c3p0.version>0.9.1.2</c3p0.version> <mysql.version>5.1.6</mysql.version> </properties> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>${c3p0.version}</version> </dependency> <!-- c3p0 end --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- <dependency>--> <!-- <groupId>org.slf4j</groupId>--> <!-- <artifactId>slf4j-api</artifactId>--> <!-- <version>1.7.30</version>--> <!-- </dependency>--> <!-- <dependency>--> <!-- <groupId>org.slf4j</groupId>--> <!-- <artifactId>slf4j-log4j12</artifactId>--> <!-- <version>1.6.6</version>--> <!-- </dependency>--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- spring data jpa 的坐标--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>2.3.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- el beg 使用spring data jpa 必须引入 --> <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>2.2.5</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>2.2.6</version> </dependency> </dependencies>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"> <!--spring 和 spring data jpa的配置--> <!-- 1.创建entityManagerFactory对象交给spring容器管理--> <bean id="entityManagerFactoty" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <!--配置的扫描的包(实体类所在的包) --> <property name="packagesToScan" value="com.qijian.domain" /> <!-- jpa的实现厂家 --> <property name="persistenceProvider"> <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/> </property> <!--jpa的供应商适配器 --> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <!--配置是否自动创建数据库表 --> <property name="generateDdl" value="false" /> <!--指定数据库类型 --> <property name="database" value="MYSQL" /> <!--数据库方言:支持的特有语法 --> <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" /> <!--是否显示sql --> <property name="showSql" value="true" /> </bean> </property> <!--jpa的方言 :高级的特性 --> <property name="jpaDialect" > <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" /> </property> </bean> <!--2.创建数据库连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="root"></property> <property name="password" value="root"></property> <property name="jdbcUrl" value="jdbc:mysql:///jpa" ></property> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> </bean> <!--3.整合spring dataJpa base-package="com.qijian.dao" 对该包下的接口进行动态代理--> <jpa:repositories base-package="com.qijian.dao" transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactoty" ></jpa:repositories> <!--4.配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactoty"></property> </bean> <!-- 4.txAdvice--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="get*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- 5.aop--> <!-- <aop:config>--> <!-- <aop:pointcut id="pointcut" expression="execution(* com.qijian.service.*.*(..))" />--> <!-- <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />--> <!-- </aop:config>--> <!--5.声明式事务 --> <!-- 6. 配置包扫描--> <context:component-scan base-package="com.qijian" ></context:component-scan> </beans>
domain
package com.qijian.domain; import lombok.Data; import javax.persistence.*; /** * TODO 类描述 * * @author qijian. * @date 2021/7/26 14:28 */ @Data @Entity @Table(name = "cst_customer") public class Customer { /** * 客户主键 * @Id:申明是主键的配置 * @GeneratedValue配置主键的生成策略 * strategy = GenerationType.IDENTITY:自增 * public enum GenerationType{ * TABLE, * SEQUENCE, * IDENTITY, * AUTO * } * JPA提供的四种标准用法为TABLE,SEQUENCE,IDENTITY,AUTO。 * a,TABLE:使用一个特定的数据库表格来保存主键。 * b,SEQUENCE:根据底层数据库的序列来生成主键,条件是数据库支持序列。 * c,IDENTITY:主键由数据库自动生成(主要是自动增长型) mysql数据库 * d,AUTO:主键由程序控制 * @Column:配置属性和字段的映射关系 * name:数据库中字段的名称 * */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "cust_id") private Long custId; /** * 客户姓名 */ @Column(name = "cust_name") private String custName; /** * 客户来源 */ @Column(name = "cust_source") private String custSource; /** * 客户所属行业 */ @Column(name = "cust_industry") private String custIndustry; /** * 客户级别 */ @Column(name = "cust_level") private String custLevel; /** * 客户地址 */ @Column(name = "cust_address") private String custAddress; /** * 客户联系方式 */ @Column(name = "cust_phone") private String custPhone; }
dao
package com.qijian.dao; import com.qijian.domain.Customer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** * TODO 符合springdatajpa的dao层接口 * JpaRepository<操作实体类型,实体类中主键属性的类型> * 封装了基本CRUD操作 * JpaSpecificationExecutor<操作的实体类> * 封装复杂查询 * @author qijian. * @date 2021/7/27 22:28 */ public interface CustomerDao extends JpaRepository<Customer,Long> , JpaSpecificationExecutor<Customer> { }
测试
package com.qijian.domain; import com.qijian.dao.CustomerDao; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.persistence.criteria.*; import java.util.HashMap; import java.util.List; import java.util.Optional; /** * TODO 类描述 * * @author qijian. * @date 2021/7/27 22:15 */ @RunWith(SpringJUnit4ClassRunner.class)//声明spring提供的单元测试 @ContextConfiguration(locations = "classpath:applicationContext.xml")//指定spring容器的配置信息 public class TestDao { @Autowired private CustomerDao customerDao; @Test public void testSpec(){ /** * 自定义查询条件 * 1,实现Specification接口(提供泛型:查询对象类型) * 2,实现toPredicate(构造查询条件) * 3,需要借助方法参数中的两个参数 * root:获取需要查询的对象属性 * CriteriaBuilder:构造查询条件,内部封装了很多的查询条件(模糊匹配,精准匹配) * 案例:根据客户名称查询,查询客户名为指定值的用户 * 查询条件 * 1,查询方式 * criteriaBuiler对象 * 2,比较属性的名称 * root对象 */ Specification<Customer> spec = new Specification<Customer>() { public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { //获取比较额属性 Path<Object> custName = root.get("custName"); //2,构造查询条件 select * from cst_customer where cust_name = 'qijian'; Predicate predicate = criteriaBuilder.equal(custName, "qijian");//进行精准匹配 return predicate; } }; System.out.println(customerDao.findOne(spec)); } /** * 多条件查询 * 案例:根据客户(qijian)和客户所属行业查询(IT) * */ @Test public void testSpec1(){ /** * root:获取属性 * 客户名 * 所属行业 * cb:构造行业 * 1,构造客户名的精准匹配查询 * 2,构造所属行业的精准匹配查询 * 3,将以上两个查询联系起来 */ Specification<Customer> spec = new Specification<Customer>() { @Override public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { Path<Object> custName = root.get("custName");//客户名 Path<Object> custIndustry = root.get("custIndustry");//所属行业 //构造查询 //1,构造客户名的精准匹配查询 //第一个参数,path(属性),第二个参数,属性的取值 Predicate predicate = criteriaBuilder.equal(custName, "qijian"); Predicate predicate1 = criteriaBuilder.equal(custIndustry, "IT"); //2,将多个查询条件组合到一起:组合(满足条件一并且满足条件二,满足条件一或满足条件二) // Predicate and = criteriaBuilder.and(predicate, predicate1);//以与的形式匹配多个查询 Predicate or = criteriaBuilder.or(predicate, predicate1);//以或的形式匹配多个查询条件 return or; } }; // Optional<Customer> one = customerDao.findOne(spec); // System.out.println(one); List<Customer> list = customerDao.findAll(spec); for ( Customer c:list) { System.out.println(c); } } /** * 案例:完成根据客户名称的模糊查询,返回客户列表 * gt,lt,ge,le,like:得到path对象,根据path指定比较的参数类型,再进行比较 * 指定参数的类型:path.as(类型字节码对象) */ @Test public void testSpec3(){ Specification spec = new Specification<Customer>() { /** * Creates a WHERE clause for a query of the referenced entity in form of a {@link Predicate} for the given * {@link Root} and {@link CriteriaQuery}. * * @param root must not be {@literal null}. * @param query must not be {@literal null}. * @param criteriaBuilder must not be {@literal null}. * @return a {@link Predicate}, may be {@literal null}. */ @Override public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { //查询属性:客户名 Path<Object> custName = root.get("custName"); //查询方式:模糊匹配 Predicate predicate = criteriaBuilder.like(custName.as(String.class), "qijian"); return predicate; } }; // 查询所有且不排序 List<Customer> list = customerDao.findAll(spec); for (Customer customer: list ) { System.out.println(customer); } //添加拍讯 //创建排序对象,需要调用构造方法实例化sort对象 //第一个参数:排序的顺序(倒叙,正序 //Sort.Direction.DESC:倒叙 //Sort.Direction.ASC:正序 //第二各参数:排序的属性名称 //'Sort(org.springframework.data.domain.Sort.Direction, java.util.List<java.lang.String>)' // has private access in 'org.springframework.data.domain.Sort // Sort sort = new Sort(Sort.Direction.DESC,"custId");//方法已被私有化不能使用了、 // List list1 = customerDao.findAll(spec); // Sort sort = Sort.by(list1); // List<Customer> list = customerDao.findAll(spec,sort); // for (Customer c : // list) { // System.out.println(c); // } } /** * 分页查询 * Specification:查询条件 * Pageable:分页参数 * 分页参数:查询的页码 ,每一页查询的条数 * findAll(Specification.Pageable):带有条件的分页 * findAll(Pageable):没有条件的分页 * 返回:page(springDataJpa为我们封装好的page对象,数据列表,还可以获取总条数等) */ @Test public void testSpec4(){ /** * 创建PageRequest的过程,需要调用他额构造方法来闯入两个参数 * (说明:我目前的编程环境是<hibernate.version>5.0.7.Final</hibernate.version>, * PageRequest的构造方法已经被定义为protect,换用PageRequest.of(0,2);) * 第一个参数:当前查询的页数(从0开始) * 第二个参数:每页查询的数量 */ // Pageable pageable = new PageRequest(0,2);//该版本中此方法已经定义成protect我们已经不能进行访问 Pageable pageable = PageRequest.of(0,3); //分页查询 Page<Customer> page = customerDao.findAll(pageable); // page.getTotalElements()得到数据库中的总条数 System.out.println(page.getTotalElements()); // page.getContent()得到总条数 System.out.println(page.getContent()); // page.getTotalPages()得到总页数 System.out.println(page.getTotalPages()); } }