All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.smart.data.repository.pagination.PaginationHelper Maven / Gradle / Ivy

There is a newer version: 4.0.14-RELEASE
Show newest version
package org.smart.data.repository.pagination;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

/**
 * @author Ranzy Blessings (2017/05/10)
 */
@SuppressWarnings("unchecked")
public class PaginationHelper {

    public Page retrievePages(
            final NamedParameterJdbcOperations jdbcOperations,
            final String sqlCountRows,
            final String sqlFetchRows,
            final SqlParameterSource parameterSource,
            final int pageNumber,
            final int pageSize,
            final RowMapper rowMapper) {

        // determine how many table rows are available
        final int rowCount = jdbcOperations.queryForObject(sqlCountRows, new HashMap(), Integer.class);

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

        // create the page object instance
        final Page page = new Page();
        page.setPageNumber(pageNumber);
        page.setPagesAvailable(pageCount);
        boolean hasNext = pageNumber < pageCount;
        boolean hasPrevious = pageNumber > 1;
        page.setHasNext(hasNext);
        page.setHasPrevious(hasPrevious);

        // retrieve a single page of results
        final int startRow = (pageNumber - 1) * pageSize;
        jdbcOperations.query(
                sqlFetchRows,
                parameterSource,
                new ResultSetExtractor() {
                    @Override
                    public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException {
                        final List pageItems = page.getPageItems();
                        int currentRow = 0;
                        while (resultSet.next() && currentRow < startRow + pageSize) {
                            if (currentRow >= startRow) {
                                pageItems.add(rowMapper.mapRow(resultSet, currentRow));
                            }
                            currentRow++;
                        }
                        return page;
                    }
                });
        return page;
    }
}