方式一:通过sql语句实现分页
// map接口
ArrayList<ExcelZhrjAlarmInfoDTO> selectZhrjAlarmInfosPageByType(@Param("start") int start,@Param("end") int end,@Param("type") int type);
// xml文件
<select id="selectZhrjAlarmInfosPageByType" resultType="com.zhrj.exam.dto.ExcelZhrjAlarmInfoDTO" parameterType="int">
select ifnull(B.dept_name,A.dept_id) as deptName,A.wan_ip,A.event_time,A.event_type,A.event_status,A.event_reasons
from zhrj_alarm_info A
left join zhrj_dept B on A.dept_id = B.dept_id
where A.event_type = #{type}
limit #{end} offset #{start}
</select>
方式二:实现Interceptor接口
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import java.util.Properties;
@Intercepts({@Signature(
type = Executor.class,
method = "query",
args = {MappedStatement.class, Object.class}
)})
public class PaginationInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement mappedStatement = (MappedStatement) args[0];
// 判断是否需要分页
if (mappedStatement.getId().contains("ByPage")) {
Object parameter = args[1];
PageParam pageParam = null;
if (parameter instanceof PageParam) {
pageParam = (PageParam) parameter;
} else if (parameter instanceof Map) {
Map<String, Object> paramMap = (Map<String, Object>) parameter;
if (paramMap.containsKey("page") && paramMap.containsKey("pageSize")) {
pageParam = new PageParam((Integer) paramMap.get("page"), (Integer) paramMap.get("pageSize"));
paramMap.put("pageParam", pageParam);
}
}
if (pageParam != null) {
String originalSql = mappedStatement.getBoundSql(parameter).getSql();
String countSql = "SELECT COUNT(1) FROM (" + originalSql + ") AS total";
PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
args[0] = MappedStatementUtils.copyFromMappedStatement(mappedStatement, (sqlSession) ->
sqlSession.getConfiguration().getMappedStatement(mappedStatement.getId() + "Count", false, true)
);
args[1] = parameter;
Object result = invocation.proceed();
pageParam.setTotal((Long) ((List<?>) result).get(0));
args[0] = MappedStatementUtils.copyFromMappedStatement(mappedStatement, (sqlSession) ->
sqlSession.getConfiguration().getMappedStatement(mappedStatement.getId(), false, true)
);
args[1] = parameter;
PageHelper.clearPage();
return invocation.proceed();
}
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// 配置初始化时的属性
}
}
然后,在MyBatis的配置文件中添加该Interceptor:
<plugins>
<plugin interceptor="your.package.name.PaginationInterceptor"/>
</plugins>