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;
}
@Override
public 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 {
@Autowired
private UserRepository userRepository;
@Override
public User findOne(Specification<User> spec) {
return userRepository.findOne(spec);
}
@Override
public List<User> findAll(Specification<User> spec) {
return userRepository.findAll(spec);
}
@Override
public Page<User> findAll(Specification<User> spec, Pageable pageable) {
return userRepository.findAll(spec, pageable);
}
@Override
public 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 {
@Autowired
private UserService userService;
/**
* 查询名字叫'曹操'的用户
*/
@Test
public void findOne() {
Specification<User> spe = new Specification<User>() {
/**
* @return Predicate: 定义了查询条件。
* @param Root<Users> root: 根对象, 封装了查询条件的对象。
* @param CriteriaQuery<?> query: 定义了一个基本的查询, 一般不使用。
* @param CriteriaBuilder cb: 创建一个查询条件。
*/
@Override
public 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);
}
/**
* 查询名字叫'曹操'和性别为'男'的用户
*/
@Test
public void findOneByNameAndSex() {
Specification<User> spe = new Specification<User>() {
@Override
public 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);
}
/**
* 查询名字叫'曹操'和住址为'安徽省亳州市'的用户
*/
@Test
public void findOneByNameAndAddress() {
Specification<User> spe = new Specification<User>() {
@Override
public 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);
}
/**
* 查询名字叫'曹操'或'曹植'的用户
*/
@Test
public void findByNameOr() {
Specification<User> spe = new Specification<User>() {
@Override
public 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);
}
}
/**
* 查询姓李的用户
*/
@Test
public void findByNameLike() {
Specification<User> spe = new Specification<User>() {
@Override
public 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之间的用户
*/
@Test
public void pageable() {
Specification<User> spe = new Specification<User>() {
@Override
public 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
*/
@Test
public void sort() {
Specification<User> spe = new Specification<User>() {
@Override
public 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
*/
@Test
public void pageableAndSort() {
Specification<User> spe = new Specification<User>() {
@Override
public 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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://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