1. 创建一个名为spring-data-jpa-specification-executor的Java项目, 同时添加相关jar包, 并添加JUnit能力。

2. 查看JpaSpecificationExecutor接口下的方法

3. 新建User.java

package com.bjbs.pojo;import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.format.annotation.DateTimeFormat;@Entity // 指定该类是实体类
@Table(name = "user") // 指定数据库表名(表名和实体类对应)
public class User implements Serializable {private static final long serialVersionUID = 1L;@Id // 指定为主键@GeneratedValue(strategy = GenerationType.IDENTITY) // 指定主键生成策略@Column(name = "id") // 指定表中列名(列名和属性名对应)private Integer id;@Column(name = "name")private String name;@Column(name = "sex")private String sex;@Column(name = "birthday")@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date birthday;@Column(name = "address")private String address;public User() {}public User(String name, String sex, Date birthday, String address) {this.name = name;this.sex = sex;this.birthday = birthday;this.address = address;}public User(Integer id, String name, String sex, Date birthday, String address) {this.id = id;this.name = name;this.sex = sex;this.birthday = birthday;this.address = address;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address+ "]";}
}

4. 新建UserRepository.java, 实现Repository和JpaSpecificationExecutor接口。

package com.bjbs.dao;import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.Repository;
import com.bjbs.pojo.User;/*** 参数一T: 当前需要映射的实体; 参数二 T: 当前映射的实体中的id的类型*/
public interface UserRepository extends Repository<User, Integer>, JpaSpecificationExecutor<User> {}

5. 新建UserService.java

package com.bjbs.service;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;
import com.bjbs.pojo.User;public interface UserService {public User findOne(Specification<User> spec);public List<User> findAll(Specification<User> spec);public Page<User> findAll(Specification<User> spec, Pageable pageable);public List<User> findAll(Specification<User> spec, Sort sort);
}

6. 新建UserServiceImpl.java

package com.bjbs.service.impl;import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bjbs.dao.UserRepository;
import com.bjbs.pojo.User;
import com.bjbs.service.UserService;@Service
@Transactional
public class UserServiceImpl implements UserService {@Autowiredprivate UserRepository userRepository;@Overridepublic User findOne(Specification<User> spec) {return userRepository.findOne(spec);}@Overridepublic List<User> findAll(Specification<User> spec) {return userRepository.findAll(spec);}@Overridepublic Page<User> findAll(Specification<User> spec, Pageable pageable) {return userRepository.findAll(spec, pageable);}@Overridepublic List<User> findAll(Specification<User> spec, Sort sort) {return userRepository.findAll(spec, sort);}}

7. 新建TestUserRepository.java

package com.bjbs.test;import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
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.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.bjbs.pojo.User;
import com.bjbs.service.UserService;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestUserRepository {@Autowiredprivate UserService userService;/*** 查询名字叫'曹操'的用户*/@Testpublic void findOne() {Specification<User> spe = new Specification<User>() {/*** @return Predicate: 定义了查询条件。* @param Root<Users> root: 根对象, 封装了查询条件的对象。* @param CriteriaQuery<?> query: 定义了一个基本的查询, 一般不使用。* @param CriteriaBuilder cb: 创建一个查询条件。*/@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {Predicate pre = cb.equal(root.get("name"), "曹操");return pre;}};User userDb = userService.findOne(spe);System.out.println(userDb);}/*** 查询名字叫'曹操'和性别为'男'的用户*/@Testpublic void findOneByNameAndSex() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {List<Predicate> list = new ArrayList<Predicate>();list.add(cb.equal(root.get("name"), "曹操"));list.add(cb.equal(root.get("sex"), "男"));Predicate[] arr = new Predicate[list.size()];return cb.and(list.toArray(arr));}};User userDb = userService.findOne(spe);System.out.println(userDb);}/*** 查询名字叫'曹操'和住址为'安徽省亳州市'的用户*/@Testpublic void findOneByNameAndAddress() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {return cb.and(cb.equal(root.get("name"), "曹操"), cb.equal(root.get("address"), "安徽省亳州市"));}};User userDb = userService.findOne(spe);System.out.println(userDb);}/*** 查询名字叫'曹操'或'曹植'的用户*/@Testpublic void findByNameOr() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {return cb.or(cb.equal(root.get("name"), "曹操"), cb.equal(root.get("name"), "曹植"));}};List<User> list = userService.findAll(spe);for (User user : list) {System.out.println(user);}}/*** 查询姓李的用户*/@Testpublic void findByNameLike() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {return cb.like(root.get("name"), "李%");}};List<User> list = userService.findAll(spe);for (User user : list) {System.out.println(user);}}/*** 分页查询id在47和51之间的用户*/@Testpublic void pageable() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {return cb.between(root.get("id"), 47, 51);}};Pageable pageable = new PageRequest(0, 5);Page<User> list = userService.findAll(spe, pageable);for (User user : list) {System.out.println(user);}}/*** 排序查询id>51*/@Testpublic void sort() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {return cb.greaterThan(root.get("id"), 51);}};Sort sort = new Sort(Direction.DESC, "id");List<User> list = userService.findAll(spe, sort);for (User user : list) {System.out.println(user);}}/*** 分页排序查询id>=51*/@Testpublic void pageableAndSort() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {return cb.ge(root.get("id"), 51);}};Sort sort = new Sort(Direction.DESC, "id");Pageable pageable = new PageRequest(0, 3, sort);Page<User> list = userService.findAll(spe, pageable);for (User user : list) {System.out.println(user);}}
}

8. 在src下新建application.properties

spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.25.138:3306/StudyMybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=lyw123456

9. 在src下新建applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:jpa="http://www.springframework.org/schema/data/jpa"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 配置读取properties文件的工具类 --><context:property-placeholder location="classpath:application.properties" /><!-- 配置c3p0数据库连接池 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="jdbcUrl" value="${spring.datasource.url}" /><property name="driverClass" value="${spring.datasource.driverClassName}" /><property name="user" value="${spring.datasource.username}" /><property name="password" value="${spring.datasource.password}" /></bean><!-- Spring整合JPA 配置EntityManagerFactory --><bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"><property name="dataSource" ref="dataSource" /><property name="jpaVendorAdapter"><bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"><!-- hibernate相关的属性的注入 --><!-- 配置数据库类型 --><property name="database" value="MYSQL" /><!-- 正向工程 自动创建表 --><!-- <property name="generateDdl" value="true" /> --><!-- 显示执行的SQL --><property name="showSql" value="true" /></bean></property><!-- 扫描实体的包 --><property name="packagesToScan"><list><value>com.bjbs.pojo</value></list></property></bean><!-- 配置Hibernate的事务管理器 --><bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"><property name="entityManagerFactory" ref="entityManagerFactory" /></bean><!-- 配置开启注解事务处理 --><tx:annotation-driven transaction-manager="transactionManager" /><!-- 配置springIOC的注解扫描 --><context:component-scan base-package="com.bjbs.service" /><!-- Spring Data JPA 的配置 --><!-- base-package: 扫描dao接口所在的包 --><jpa:repositories base-package="com.bjbs.dao" />
</beans>

10. 数据库user表

11. 查询名字叫'曹操'的用户

12. 查询名字叫'曹操'和性别为'男'的用户

13. 查询名字叫'曹操'和住址为'安徽省亳州市'的用户

14. 查询名字叫'曹操'或'曹植'的用户

15. 查询姓'李'的用户

16. 分页查询id在47和51之间的用户

17. 排序查询id>51

18. 分页排序查询id>=51

005_Spring Data JPA条件查询相关推荐

  1. Spring data jpa 条件查询-按时间段查询

    Spring data jpa 条件查询-按时间段查询 @Overridepublic Page<泛型> findRecordList(int couponDetailId, int pa ...

  2. Spring Data JPA 条件查询的关键字

    Spring Data JPA 为此提供了一些表达条件查询的关键字,大致如下: And --- 等价于 SQL 中的 and 关键字,比如 findByUsernameAndPassword(Stri ...

  3. Spring Data JPA 条件查询 分页查询

    条件查询 //Label : 实体类,传过来的参数 labelDao.findAll(new Specification<Label>(){@Overridepublic Predicat ...

  4. SpringData JPA条件查询、排序、分页查询

    前言 在刚开始学习的时候,在dao的定义的接口需要继承JpaRepository<T, ID>接口和JpaSpecificationExecutor< T >接口,但是一直以来 ...

  5. Spring Data JPA 实例查询

    转自:https://www.cnblogs.com/rulian/p/6533109.html 一.相关接口方法 在继承JpaRepository接口后,自动拥有了按"实例"进行 ...

  6. mysql jpa 正则_Spring Data JPA 实例查询

    数量:1 刘芳 三.认识"实例查询" 1.概念定义: 上面例子中,是这样创建"实例"的:Example ex = Example.of(customer, ma ...

  7. Spring Data JPA分页查询

    使用Spring Data JPA的朋友,在实际工作中经常需要用到分页查询.下面介绍一个简单的分页查询的例子:查询学生信息,每页10行数据,并按成绩排序.先看数据表: 实现:repo需要继承Pagin ...

  8. Spring data jpa 动态查询封装

    最近几天学习一下jpa,发现在动态查询方面支持不是很好,一个包含多种动态查询条件的列表需要写大量的代码,而我本身有强迫症,代码有洁癖,大量的重复的代码,自然不爽,于是就.......,废话少说,直接上 ...

  9. spring data jpa 分页查询

    法一(本地sql查询,注意表名啥的都用数据库中的名称,适用于特定数据库的查询) public interface UserRepository extends JpaRepository<Use ...

最新文章

  1. 《PHP和MySQL Web开发》学习之二--数据的存储与检索
  2. Asp.net控件开发学习笔记(六)----数据回传
  3. 分布式消息流平台:不要只想着Kafka,还有Pulsar
  4. Unity Lighting(一)光照练习
  5. LR mobile HTTP/HTML协议实战
  6. python mysql 循环语句怎么写_用于mysql语句的Python循环
  7. 单链表的实现 (C语言版 数据结构 严蔚敏)
  8. 【锐捷交换机】清除密码
  9. vnc远程桌面,vnc远程桌面使用教程图解
  10. c语言在电路设计作用,ds1307怎么使用(ds1307引脚图及功能_c语言程序及典型应用电路)...
  11. 计算机如何操作补考,关于计算机Excel补考试题
  12. nginx源码分析--master和worker进程模型
  13. 如何做云班课上的计算机作业,云班课不分组怎么提交作业
  14. 分解成质因数(如435234=251*17*17*3*2
  15. 你知道中国大陆一共有多少IPv4地址吗?
  16. 自行车改装电动车怎么样_电动车听起来应该是什么样?
  17. NGINX做反向代理缓存服务器原理
  18. RFID智能仓储管理解决方案-RFID无人仓储管理-新导智能
  19. 有哪些设备管理软件值得推荐?
  20. Python源码怎么运行?

热门文章

  1. Retrofit2.0和Rxjava结合使用的简单记录
  2. IT员工应该向谁汇报工作,CFO or CEO?
  3. 手机版本高于xcode,xcode的快速升级
  4. Nginx配置文件nginx.conf (Apache)
  5. 小菜鸟学 Spring-Dependency injection(二)
  6. http://www.raytracegroundup.com/downloads.html 对该页的翻译。
  7. Windows Server 2012 R2/2016 此工作站和主域间的信任关系失败
  8. 解惑:为什么云计算和物联网会同时出现——微云网络
  9. 使用VS进行远程调试
  10. 【敏捷测试】一个测试人员在参与敏捷测试的经验分享(3)