springDataJpa——spectification查询
一、环境搭建
springDataJpa的环境搭建在上篇已经讲到,这篇中所使用的entity、Dao与层下面这个链接一致,这里不再赘述。springDataJpa环境搭建
二、使用测试
package com.xsl.test;
import com.xsl.dao.UserDao;
import com.xsl.entity.UserEntity;
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.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
/**
* 自定义查询条件
* 1、实现Specification接口(提供泛型,查询的对象类型)
* 2、实现toPredicate方法(构造查询条件)
* 3、需要借助方法参数中的两个参数
* root:获取需要查询的对象属性,
* CriteriaBuilder:用件的来构造查询条,内部封装了很多的查询条件(模糊查询、精准匹配)
*/
public class SpecificationsQuery {
@Autowired
private UserDao userDao;
/**
* equal方式多条件
*/
@Test
public void testSpecification(){
Specification<UserEntity> spec = new Specification<UserEntity>() {
@Override
public Predicate toPredicate(Root<UserEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
//获取比较的属性
Path<Object> username = root.get("username");
//构造查询条件
Predicate predicate1 = criteriaBuilder.equal(username, "东软慧聚");
Path<Object> password = root.get("password");
//使用equal方法直接使用Path即可
Predicate predicate2 = criteriaBuilder.equal(password, "123");
Predicate and = criteriaBuilder.and(predicate1,predicate2);
return and;
}
};
List<UserEntity> all = userDao.findAll(spec);
System.out.println(all);
}
/**
* like方式模糊查询
*/
@Test
public void testSpecLike(){
Specification<UserEntity> tSpecification = new Specification<UserEntity>() {
@Override
public Predicate toPredicate(Root<UserEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
Path<Object> username = root.get("username");
//除了equal方法,需要使用Path.as(类型字节码的方式)
Predicate like = criteriaBuilder.like(username.as(String.class), "%东软慧聚%");
return like;
}
};
List<UserEntity> all = userDao.findAll(tSpecification);
System.out.println(all);
}
/**
* 排序
*/
@Test
public void sort(){
Sort orders = new Sort(Sort.Direction.DESC,"id");
List<UserEntity> all = userDao.findAll(orders);
System.out.println(all);
}
/**
* 分页查询
*/
@Test
public void page(){
Pageable pageable = new PageRequest(0,1);
Page<UserEntity> all = userDao.findAll(pageable);
List<UserEntity> content = all.getContent();
//内容
System.out.println(content);
//总记录数
System.out.println(all.getTotalElements());
//总页数
System.out.println(all.getTotalPages());
}
}