yml文件
server:
port: 8081
mybatis:
mapper-locations: classpath:mapper/*.xml
config-location: classpath:mybatis-config.xml
spring:
datasource:
password: 1234
username: root
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&serverTimezone=UTC
mybatis配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<plugins>
<plugin interceptor="com.dls.config.PageInterceptor"></plugin>
</plugins>
</configuration>
分页类
package com.dls.config;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Page {
Integer page;
Integer size;
}
分页工具类(保存分页数据)
package com.dls.config;
public class PageUtil {
private static ThreadLocal<Page> PAGE_THREADLOCAL = new ThreadLocal<Page>();
public static void setPage(Integer page,Integer size) {
Page page1 = new Page(page, size);
PAGE_THREADLOCAL.set(page1);
}
public static Page getPage() {
return PAGE_THREADLOCAL.get();
}
public static void remove() {
PAGE_THREADLOCAL.remove();
}
}
分页插件类
package com.dls.config;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;
@Intercepts(
@Signature(type = StatementHandler.class,method = "prepare",args = {Connection.class,Integer.class})
)
@Slf4j
public class PageInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
Page page = PageUtil.getPage();
if (page == null) {
return invocation.proceed();
}
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
BoundSql boundSql = statementHandler.getBoundSql();
String sql = boundSql.getSql();
String limit = String.format(" limit %s,%s",(page.getPage() - 1) * page.getSize(),page.getSize());
sql += limit;
Field field = boundSql.getClass().getDeclaredField("sql");
field.setAccessible(true);
field.set(boundSql,sql);
field.setAccessible(false);
Object proceed = invocation.proceed();
PageUtil.remove();
return proceed;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target,this);
}
@Override
public void setProperties(Properties properties) {
}
}
设置分页参数
控制台sql信息发现分页插件已经生效
==> Preparing: select * from student limit 0,3
==> Parameters:
<== Columns: id, password, username
<== Row: 1, 660779, dls
<== Row: 2, 2, 9
<== Row: 3, 666, 777
<== Total: 3