使用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<Customer> 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<Customer> 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<Customer> customers = customDao.findAll(specification, new Sort(Sort.Direction.DESC, "cId"));
        for (Customer customer : customers) {
            System.out.println(customer);
        }
    }

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

}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值