在代码中使用分页:PageHelper.startPage方法
// Page类有两个,一个是PageHelper的Page类,另一个是自定义的Page类
public Page<T> queryForPageList(T entity, Page<T> page) {
com.github.pagehelper.Page<T> pageTemp = PageHelper.startPage(page.getPageNumber(), page.getPageSize(), true);
this.queryForList(entity);
page.setTotal(pageTemp.getTotal());
page.setRows(pageTemp.getResult());
return page;
}
public List<T> queryForList(T entity) {
return this.getSqlSession().selectList(this.obtainNameSpace(entity.getClass()) + ".selectAll", this.buildMap(entity.getClass(), entity));
}
sql语句的改写,涉及到两个类:OracleParser, MysqlParser
OracleParser类
public class OracleParser extends AbstractParser {
@Override
public String getPageSql(String sql) {
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 120);
sqlBuilder.append("select * from ( select tmp_page.*, rownum row_id from ( ");
sqlBuilder.append(sql);
sqlBuilder.append(" ) tmp_page where rownum <= ? ) where row_id > ?");
return sqlBuilder.toString();
}
@Override
public Map<String, Object> setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page<?> page) {
Map<String, Object> paramMap = super.setPageParameter(ms, parameterObject, boundSql, page);
paramMap.put(PAGEPARAMETER_FIRST, page.getEndRow());
paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow());
return paramMap;
}
}
MysqlParser类
public class MysqlParser extends AbstractParser {
@Override
public String getPageSql(String sql) {
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
sqlBuilder.append(sql);
sqlBuilder.append(" limit ?,?");
return sqlBuilder.toString();
}
@Override
public Map<String, Object> setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, Page<?> page) {
Map<String, Object> paramMap = super.setPageParameter(ms, parameterObject, boundSql, page);
paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
return paramMap;
}
}
网友评论