How to combine pagination with a criteria query in Spring Data JPA?

后端 未结 2 1637
旧巷少年郎
旧巷少年郎 2021-02-13 06:30

I use PagingAndSortingRepository and findAll(Pageable pageable) method to paging my data. I think that there is no way to provide any condition. For example sometime I want sele

2条回答
  •  旧巷少年郎
    2021-02-13 07:08

    For Pagination you need 2 methods like getCount(Pageable pageable) and findAll(Pageable pageable)

    Utilizing this functionality in Hibernate, however, is trivial. If you have any HQL query you can simply do this:

    public Long getCount(Pageable pageable) {
        Query q = session.createQuery("Select count(t) From TableClass  t where t.city = 'NY'");
        Long cnt = (Long) q.uniqueResult();
        return cnt;
    }
    
    public List findAll(Pageable pageable) {
         Query q = session.createQuery("From TableClass  t where t.city = 'NY'");
         q.setFirstResult(start);
         q.setMaxResults(length);
         List tableClasslist = q.list();
         return tableClasslist;
    }
    

    Likewise, if you have a Criteria query, it's effectively the same thing:

    public Long getCount(Pageable pageable) {
        Criteria c = session.createCriteria(TableClass.class);
        c.setProjection(Projections.rowCount()); 
        Long cnt = (Long) c.uniqueResult();
        return cnt;
    }
    
    public List findAll(Pageable pageable) {
        Criteria c = session.createCriteria(TableClass.class);
        c.setParameter("city","NY");
        c.setFirstResult(start);
        c.setMaxResults(length);
        List tableClasslist = c.list();
        return tableClasslist ;
    }
    

提交回复
热议问题