基与上一篇文章 SpringData JPA 入门小 demo , 我们继续深入了解 Specifications 动态查询.
基于上一篇文章所建立的开发环境, 我们接着创建新的测试包, 来学习 Specifications 接口动态查询入门小 demo
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpecTest {
@Autowired
private CustomerDao customerDao;
}
1. 单条件查询对象 - equal(String str, String str);
@Test
public void testFindByCondition() {
Specification spec = new Specification() {
public Predicate toPredicate(Root root, CriteriaQuery> query, CriteriaBuilder cb) {
Path
2. 多条件查询对象 - and(Predicate p1, Predicate p2); or(Predicate p1, Predicate p2);
@Test
public void testFindBySeveralCondition() {
Specification spec = new Specification() {
public Predicate toPredicate(Root root, CriteriaQuery> query, CriteriaBuilder cb) {
Path
3. 模糊查询 - like();
排序 - Sort sort = new Sort(Sort.Direction.DESC, 排序的字段名);
@Test
public void testLike() {
Specification spec = new Specification() {
public Predicate toPredicate(Root root, CriteriaQuery> query, CriteriaBuilder cb) {
Path custName = root.get("custName");
Predicate like = cb.like(custName.as(String.class), "张%");
return like;
}
};
//添加排序
//Sort.Direction.DESC: 倒序
//Sort.Direction.ASC: 升序
Sort sort = new Sort(Sort.Direction.DESC, "custName");
List list = customerDao.findAll(spec, sort);
for (Customer customer : list) {
System.out.println(customer);
}
}
4. 分页查询
@Test
public void testPage() {
Specification spec = null;
Pageable pageable = new PageRequest(0, 10);
Page page = customerDao.findAll(null, pageable);
System.out.println(page.getContent()); //得到数据集合列表
System.out.println(page.getTotalElements()); //得到总条数
System.out.println(page.getTotalPages()); //得到总页数
}
源码下载: https://pan.baidu.com/s/1JLc4zABzZBzoy4JhJNNJpg