欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring data jpa分页

程序员文章站 2022-04-25 11:20:05
...

一、JpaRepository中定义方法

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface ContractDao extends JpaRepository<Contract,Integer> {

    Page<Contract> findAll(Specification<Contract> spec, Pageable pageable);

}

二、分页方法

 public Page<Contract> findContractByName(String viName, Pageable pageable) {
        System.out.println(viName);
        Specification<Contract> sp = new Specification<Contract>() {
            public Predicate toPredicate(Root<Contract> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                Path<String> name = root.get("contractName");
                Predicate p = cb.like(name,"%"+viName+"%");
                list.add(p);
                return p;
            }
        };
        return contractDao.findAll(sp, pageable);
    }

三、controller

 /**
     * 分页查询合同信息
     */
    @GetMapping(value = "contract/find")
    public Page<Contract> findContractByName(@RequestParam("name") String name,@RequestParam("current") int current) {
        System.out.println(current);
        Pageable pageable=new PageRequest(current-1, 10);  //分页信息
        return contractService.findContractByName(name,pageable);
    }