JpaSpecificationExecutor自带方法:
public interface JpaSpecificationExecutor<T> {
// 查询单个对象
Optional<T> findOne(@Nullable Specification<T> var1);
// 查询列表
List<T> findAll(@Nullable Specification<T> var1);
// 查询全部(分页):pageable(分页参数)
Page<T> findAll(@Nullable Specification<T> var1, Pageable var2);
// 查询列表(Sort:排序参数)
List<T> findAll(@Nullable Specification<T> var1, Sort var2);
// 统计查询
long count(@Nullable Specification<T> var1);
}
自定义查询条件:
1、实现Specification接口(提供泛型:查询的对象类型);
2、实现toPredicate方法(构造查询条件);
3、需要借助方法参数中的两个参数(root:获取需要查询的对象属性,CriteriaBuilder:用于构造查询条件,内部封装了很多查询条件,如模糊匹配、精准匹配等);
@RunWith(SpringJUnit4ClassRunner.class)//声明Spring提供的单元测试环境
@ContextConfiguration(locations = "classpath:applicationContext.xml")//指定spring容器的配置信息
public class CustomerDaoTest {
@Autowired
private CustomerDao customerDao;
@Test
public void testSpec() {
Specification<Customer> spec = new Specification<Customer>() {
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
// 1、获取比较的属性
Path<Object> custName = root.get("custName");
// 2、构造查询条件
Predicate predicate = criteriaBuilder.equal(custName, "测试名称");
return predicate;
// 模糊查询
// gt(greater than),lt(less than),ge(greater than or equal),lt(less than or equal),like:得到path对象,根据path指定比较的参数类型,再去进行比较
// 指定参数类型:path.as(类型的字节码对象)
Predicate like = criteriaBuilder.like(custName.as(String.class), "测试名称");
}
};
Customer customer = customerDao.findOne(spec);
System.out.println(customer );
}
// 模糊查询
@Test
public void testSpec() {
Specification<Customer> spec = new Specification<Customer>() {
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
// 获取比较的属性
Path<Object> custName = root.get("custName");
// gt(greater than),lt(less than),ge(greater than or equal),lt(less than or equal),like:得到path对象,根据path指定比较的参数类型,再去进行比较
// 指定参数类型:path.as(类型的字节码对象)
Predicate like = criteriaBuilder.like(custName.as(String.class), "测试名称%");
return like;
}
};
List<Customer> customers = customerDao.findAll(spec);
for (Customer customer : customers) {
System.out.println(customer);
}
// 添加排序
// 创建排序对象,需要调用构造方法实例化sort对象
// 参数1:排序顺序(正序、倒序):Sort.Diredction.ASC(正序);Sort.Direction.DESC(倒序)
// 参数2:排序的属性名称
// Sort sort = new Sort(Sort..Direction.DESC, "custId");
// List<Customer> list = customerDao.findAll(spec,sort);
}
// 分页查询
// Specification:查询条件
// Pageable:分页参数(查询的页码,每页查询的条数)
// findAll(Specification, Pageable):带条件的分页
// findAll(Pageable):无条件的分页
// 返回:Page(Spring data jpa已封装好的pageBean对象,数据列表,总条数)
@Test
public void testPage() {
Specification spec = null;
Pageable pageable = new PageRequest(0, 2);
Page<Customer> page = customerDao.findAll(null, pageable);
// 数据列表
System.out.println(page.getContent());
// 总条数
System.out.println(page.getTotalElements);
// 总页数
System.out.println(page.getTotalPages());
}
}