Spring JDBC Pagination Tutorial

原文链接:http://www.codefutures.com/tutorials/spring-pagination/

Example

This tutorial uses the use code of listing a number of companies. This might be a public service listing records of public companies.

Using Spring JDBC without Pagination

First of all, let's look at a standard technique using Spring JDBC to return a list of companies in a single result set.

public List<CompanygetCompanies() throws SQLException {
    return jdbcTemplate.query(
            "SELECT id, name FROM company WHERE user_id = ? AND deleted = 0 ORDER BY name",
            new ParameterizedRowMapper<Company>() {
                public Company mapRow(ResultSet rsint ithrows SQLException {
                    return new Company(
                            rs.getInt(1),
                            rs.getString(2)
                    );
                }
            },
            userId
    );
}

Using Spring JDBC with Pagination

Here's a new version of the method which uses a PaginationHelper class, which is shown further on in this tutorial. As you can see, the usage is very similar to standard Spring JDBC. The most obvious difference is that we now have two SQL statements instead of one. This is necessary if we want to be able to show the users how many pages of data there are but it is an extra performance hit so there is room for refinement in this approach by perhaps caching the number of pages. The code uses the standard ParameterizedRowMapper to minimize impact on existing code.

public Page<CompanygetCompanies(final int pageNofinal int pageSizethrows SQLException {
        PaginationHelper<Companyph = new PaginationHelper<Company>();
        return ph.fetchPage(
                jdbcTemplate,
                "SELECT count(*) FROM company WHERE user_id = ? AND deleted = 0 ORDER BY name",
                "SELECT id, name FROM company WHERE user_id = ? AND deleted = 0 ORDER BY name",
                new Object[]{userId},
                pageNo,
                pageSize,
                new ParameterizedRowMapper<Company>() {
                    public Company mapRow(ResultSet rsint ithrows SQLException {
                        return new Company(
                            rs.getInt(1),
                            rs.getString(2)
                        );
                    }
                }
        );

    }

The Page class

The Page class is a very simple template class that contains a list of items, the page number, and the number of pages that are available.

public class Page<E> {

        private int pageNumber;
        private int pagesAvailable;
        private List<EpageItems = new ArrayList<E>();

        public void setPageNumber(int pageNumber) {
            this.pageNumber = pageNumber;
        }

        public void setPagesAvailable(int pagesAvailable) {
            this.pagesAvailable = pagesAvailable;
        }

        public void setPageItems(List<EpageItems) {
            this.pageItems = pageItems;
        }

        public int getPageNumber() {
            return pageNumber;
        }

        public int getPagesAvailable() {
            return pagesAvailable;
        }

        public List<EgetPageItems() {
            return pageItems;
        }
    }

Pagination Helper

Here's the source code for the PaginationHelper class. This is actually very simple. The first SQL query is executed to determine how many rows of data are available. This allows the number of pages to be calculated. The second query is then executed using the JdbcTemplate query method that accepts a Spring ResultSetExtractor. The implementation of this ResultSetExtractor processes the result set and delegates to the supplied ParameterizedRowMapper for those rows that should be returned as part of the current page of data.

public class PaginationHelper<E> {

    public Page<EfetchPage(
            final JdbcTemplate jt,
            final String sqlCountRows,
            final String sqlFetchRows,
            final Object args[],
            final int pageNo,
            final int pageSize,
            final ParameterizedRowMapper<ErowMapper) {

        // determine how many rows are available
        final int rowCount = jt.queryForInt(sqlCountRowsargs);

        // calculate the number of pages
        int pageCount = rowCount / pageSize;
        if (rowCount > pageSize * pageCount) {
            pageCount++;
        }

        // create the page object
        final Page<Epage = new Page<E>();
        page.setPageNumber(pageNo);
        page.setPagesAvailable(pageCount);

        // fetch a single page of results
        final int startRow = (pageNo - 1) * pageSize;
        jt.query(
                sqlFetchRows,
                args,
                new ResultSetExtractor() {
                    public Object extractData(ResultSet rsthrows SQLExceptionDataAccessException {
                        final List pageItems = page.getPageItems();
                        int currentRow = 0;
                        while (rs.next() && currentRow < startRow + pageSize) {
                            if (currentRow >= startRow) {
                                pageItems.add(rowMapper.mapRow(rscurrentRow));
                            }
                            currentRow++;
                        }
                        return page;
                    }
                });
        return page;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值