如何用mybatis写一个拦截器分页
时间: 2024-05-12 14:20:51 浏览: 103
mybatis使用拦截器实现分页操作
4星 · 用户满意度95%
1. 创建一个实现了Interceptor接口的分页拦截器类
```java
public class PageInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 获取原始sql
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
Object parameter = invocation.getArgs()[1];
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
String originalSql = boundSql.getSql();
// 获取分页参数
Pageable pageable = PageableThreadLocal.getPageable();
if (pageable == null) {
// 没有分页参数,直接执行原始sql
return invocation.proceed();
}
int pageNum = pageable.getPageNum();
int pageSize = pageable.getPageSize();
// 生成分页sql
String pageSql = generatePageSql(originalSql, pageNum, pageSize);
// 替换原始sql为分页sql
Field field = boundSql.getClass().getDeclaredField("sql");
field.setAccessible(true);
field.set(boundSql, pageSql);
// 执行分页sql
Object result = invocation.proceed();
// 返回分页结果
return result;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// do nothing
}
private String generatePageSql(String originalSql, int pageNum, int pageSize) {
StringBuilder builder = new StringBuilder();
builder.append(originalSql);
builder.append(" LIMIT ");
builder.append((pageNum - 1) * pageSize);
builder.append(",");
builder.append(pageSize);
return builder.toString();
}
}
```
2. 在Mybatis配置文件中配置拦截器
```xml
<plugins>
<plugin interceptor="com.example.PageInterceptor"/>
</plugins>
```
3. 在使用分页的Mapper接口方法中设置分页参数
```java
@Select("SELECT * FROM user WHERE name LIKE #{name}")
List<User> findByName(@Param("name") String name, Pageable pageable);
```
4. 在代码中设置分页参数
```java
Pageable pageable = new Pageable(1, 10);
PageableThreadLocal.setPageable(pageable);
List<User> users = userMapper.findByName("张三");
```
阅读全文