org.smart.data.repository.pagination.PaginationHelper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of smart-data-repository Show documentation
Show all versions of smart-data-repository Show documentation
ORM that simplifies database interactions.
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