分页拦截器配置类 代码
时间: 2023-05-31 16:03:13 浏览: 53
这是一个基于 MyBatis 的分页拦截器配置类示例,可以用于实现分页查询:
```java
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.Properties;
@Intercepts(@Signature(type = org.apache.ibatis.executor.Executor.class, method = "query", args = {org.apache.ibatis.mapping.MappedStatement.class, Object.class, RowBounds.class, org.apache.ibatis.session.ResultHandler.class}))
@Component
public class PaginationInterceptor implements Interceptor {
private static final String PAGE = "page";
private static final String ROWS = "rows";
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
RowBounds rowBounds = (RowBounds) args[2];
if (rowBounds != RowBounds.DEFAULT) {
// 如果是分页查询,则进行分页处理
args[2] = new RowBounds(getOffset(rowBounds), rowBounds.getLimit());
// 将分页参数设置到 ThreadLocal 中
setPageParameter(rowBounds.getOffset(), rowBounds.getLimit());
}
return invocation.proceed();
}
private void setPageParameter(int offset, int limit) {
Map<String, Object> pageParams = PageContextHolder.getPageParams();
if (pageParams != null) {
pageParams.put(PAGE, offset / limit + 1);
pageParams.put(ROWS, limit);
}
}
private int getOffset(RowBounds rowBounds) {
return rowBounds.getOffset() <= 0 ? 0 : rowBounds.getOffset();
}
@Override
public Object plugin(Object o) {
return o instanceof org.apache.ibatis.executor.Executor ? org.apache.ibatis.plugin.Plugin.wrap(o, this) : o;
}
@Override
public void setProperties(Properties properties) {
}
}
```
在这个配置类中,我们定义了一个 `PaginationInterceptor` 拦截器,它实现了 `Interceptor` 接口,可以拦截 MyBatis 的查询方法。在 `intercept` 方法中,我们判断是否为分页查询,如果是,则进行分页处理并将分页参数设置到 `ThreadLocal` 中。在 `setPageParameter` 方法中,我们将分页参数设置到 `Map<String, Object>` 类型的 `PageContextHolder` 中,这个类是一个自定义的上下文工具类,用于存储分页参数。在 `plugin` 方法中,我们将拦截器包装成一个插件,用于拦截 MyBatis 的查询方法,最后在 Spring 容器中将这个拦截器配置为一个 Bean。