使用SpringData中的Specification进行查询

首先先搭建一个maven工程,

然后我们直接添加测试类

package com.w;

import com.w.dao.CustomDao;
import com.w.domain.Customer;
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.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(locations = "classpath:applicationContext.xml")
public class TestSpecification {
    @Autowired
    private CustomDao customDao;

    @Test
    public void testFindOne() {
        Specification specification = new Specification() {
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //属性名称
                Path cName = root.get("cName");
                //属性名称和属性值对应
                Predicate predicate = criteriaBuilder.equal(cName, "张三");
                return predicate;
            }
        };
        Customer customer = customDao.findOne(specification);
        System.out.println(customer);
    }

    @Test
    public void testFindAll() {
        Specification specification = new Specification() {
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //属性名称
                Path cName = root.get("cName");
                //属性名称和属性值对应
                Predicate predicateName = criteriaBuilder.like(cName, "张%");
                Path cAddr = root.get("cAddr");
                Predicate predicateAddr = criteriaBuilder.equal(cAddr, "杭州");
                Predicate predicate = criteriaBuilder.and(predicateName, predicateAddr);
                return predicate;
            }
        };
        //根据Id降序
        List customers = customDao.findAll(specification, new Sort(Sort.Direction.DESC, "cId"));
        for (Customer customer : customers) {
            System.out.println(customer);
        }
    }

    @Test
    public void testPageable() {
        Page page = customDao.findAll(null,new PageRequest(0,2));
        System.out.println(page.getTotalElements());
        System.out.println(page.getTotalPages());
        System.out.println(page.getContent());
    }

}

上面三个方法分别测试了条件查询,排序查询,以及分页查询,童鞋们可以根据自己的需要,进行对应的代码编写。

你可能感兴趣的:(springdata)