最近项目上使用mysql时,数据量很大,所以制定了分页的功能
1.编写model层
@Entity @Table(name = "test") public class Test { @Id private String id; private Date createTime; private Date lastChangeTime; } 省略get,set方法
2.编写dao层
@Repository("test") public interface TestDao extends JpaRepository<Test, String>, JpaSpecificationExecutor<Test> { }
3.编写service
@Service public class TestService { @Autowired private TestDao testDao; public Page<Test> findTest(Date startTime, Date endTime, int start, int limit) { Pageable pageable = new PageRequest(start, limit, Sort.Direction.ASC, "createTime"); Specification<Test> specification = (root, query, cb) -> { List<Predicate> predicates = new ArrayList<>(); predicates.add(cb.greaterThanOrEqualTo(root.get("createTime").as(Date.class), startTime)); predicates.add(cb.lessThan(root.get("createTime").as(Date.class), endTime)); Predicate[] p = new Predicate[predicates.size()]; return cb.and(predicates.toArray(p)); }; return testDao.findAll(specification, pageable); } }