最近要做Mybaits分页,选择了PageHelper插件。使用非常简单。
官网地址:https://pagehelper.github.io/
SpringBoot集成步骤:
1.pom文件中引入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
<exclusions>
<exclusion>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>
2.application.yml加入如下配置即可使用
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countSql
本文主要讲如何扩展PageHelper切换到自己的数据库。
首先我们自定义一个CustomDialect继承AbstractHelperDialect
代码如下:
@Component
public class CustomDialect extends AbstractHelperDialect {
static {
PageAutoDialect.registerDialectAlias("gbase", CustomDialect.class);
}
/* (non-Javadoc)
* @see com.github.pagehelper.dialect.AbstractHelperDialect#processPageParameter(org.apache.ibatis.mapping.MappedStatement, java.util.Map, com.github.pagehelper.Page, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey)
*/
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql,
CacheKey pageKey) {
paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
//处理pageKey
pageKey.update(page.getStartRow());
pageKey.update(page.getPageSize());
//处理参数配置
if (boundSql.getParameterMappings() != null) {
List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>();
if (boundSql != null && boundSql.getParameterMappings() != null) {
newParameterMappings.addAll(boundSql.getParameterMappings());
}
if (page.getStartRow() == 0) {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class).build());
} else {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, Integer.class).build());
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class).build());
}
MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
metaObject.setValue("parameterMappings", newParameterMappings);
}
return paramMap;
}
/* (non-Javadoc)
* @see com.github.pagehelper.dialect.AbstractHelperDialect#getPageSql(java.lang.String, com.github.pagehelper.Page, org.apache.ibatis.cache.CacheKey)
*/
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
sqlBuilder.append(sql);
if (page.getStartRow() == 0) {
sqlBuilder.append(" LIMIT ? ");
} else {
sqlBuilder.append(" LIMIT ?, ? ");
}
pageKey.update(page.getPageSize());
return sqlBuilder.toString();
}
}
getPageSql()方法里是我们的拼接分页sql查询语句,在 sqlBuilder.append(" LIMIT ?, ? ");这里将limit替换成我们新数据库语法的分页语句即可。
3.最后在我们的application.yml改为自定义的分页实现类即可使用
pagehelper:
helper-dialect: gbase
reasonable: true
support-methods-arguments: true
params: count=countSql