美文网首页
2021-11-17 分页插件PageHelper使用

2021-11-17 分页插件PageHelper使用

作者: 归去来ming | 来源:发表于2021-11-16 14:10 被阅读0次

    在代码中使用分页: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;
        }
    }
    

    相关文章

      网友评论

          本文标题:2021-11-17 分页插件PageHelper使用

          本文链接:https://www.haomeiwen.com/subject/plmltrtx.html