package com.sgcc.base.common.rest.model;
import com.github.pagehelper.Page;
import com.github.pagehelper.dialect.helper.MySqlDialect;
import com.github.pagehelper.util.MetaObjectUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.reflection.MetaObject;
/**
* dyh 2022.12.02 add
* 自定义PageHelper MySql的limit位置
*/
public class CustomPageHelperMySqlDialect extends MySqlDialect {
public static final String LIMIT_PLACEHOLDER = "/*{LIMIT}*/"; //sql关键字
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
String sql = boundSql.getSql();
if(sql.indexOf(LIMIT_PLACEHOLDER) != -1) {
String beforeLimitSql = sql.substring(0, sql.indexOf(LIMIT_PLACEHOLDER)); //获取分页之前的sql
int limitPlaceholderIndex = 0; //分页占位符的参数位置
if(beforeLimitSql.contains("?")) limitPlaceholderIndex = (beforeLimitSql.length() - beforeLimitSql.replaceAll("[?]", "").length());
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<>(boundSql.getParameterMappings());
if (page.getStartRow() == 0) {
newParameterMappings.add(limitPlaceholderIndex, new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, int.class).build());
} else {
newParameterMappings.add(limitPlaceholderIndex, new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, long.class).build());
newParameterMappings.add(limitPlaceholderIndex + 1,new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, int.class).build());
}
MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
metaObject.setValue("parameterMappings", newParameterMappings);
}
return paramMap;
}
return super.processPageParameter(ms, paramMap, page, boundSql, pageKey);
}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {
if(sql.indexOf(LIMIT_PLACEHOLDER) != -1) {
if (page.getStartRow() == 0) {
sql = sql.replace(LIMIT_PLACEHOLDER, "\n LIMIT ? ");
//sql = String.format(sql.replace(LIMIT_PLACEHOLDER, "\n LIMIT %s "), page.getPageSize());
} else {
sql = sql.replace(LIMIT_PLACEHOLDER, "\n LIMIT ?, ? ");
//sql = String.format(sql.replace(LIMIT_PLACEHOLDER, "\n LIMIT %s, %s "), page.getStartRow(), page.getPageSize());
}
return sql;
}else {
return super.getPageSql(sql, page, pageKey);
}
}
}