MybatisPlusInterceptor配置最大页数
时间: 2024-01-11 14:13:50 浏览: 94
C#获取指定PDF文件页数的方法
在 Mybatis Plus 中,可以通过配置拦截器来设置最大页数。下面是一个示例的配置:
首先,创建一个拦截器类 `MyInterceptor`,实现 `Interceptor` 接口:
```java
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import java.sql.Connection;
import java.util.Properties;
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class MyInterceptor implements Interceptor {
private static final int MAX_PAGE_SIZE = 100; // 设置最大页数为100
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
MetaObject metaStatementHandler = MetaObject.forObject(statementHandler, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, DEFAULT_REFLECTOR_FACTORY);
MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
BoundSql boundSql = statementHandler.getBoundSql();
// 获取分页参数
Object paramObj = boundSql.getParameterObject();
if (paramObj instanceof Map) {
Map<String, Object> paramMap = (Map<String, Object>) paramObj;
if (paramMap.containsKey("size") && paramMap.containsKey("current")) {
Integer size = (Integer) paramMap.get("size");
Integer current = (Integer) paramMap.get("current");
if (size != null && current != null && size > MAX_PAGE_SIZE) {
paramMap.put("size", MAX_PAGE_SIZE); // 设置最大页数
paramMap.put("current", current); // 保持当前页数不变
}
}
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
if (target instanceof StatementHandler) {
return Plugin.wrap(target, this);
}
return target;
}
@Override
public void setProperties(Properties properties) {
// do nothing
}
}
```
然后,在 MyBatis 的配置文件中,配置拦截器:
```xml
<configuration>
<plugins>
<plugin interceptor="com.example.MyInterceptor"/>
</plugins>
</configuration>
```
注意将 `com.example.MyInterceptor` 替换为你实际定义的拦截器类的完整路径。
这样,当使用 Mybatis Plus 进行分页查询时,如果请求的每页大小超过最大页数,拦截器会将每页大小设置为最大页数,并保持当前页数不变。
阅读全文