一、mapper
二、接口:
List selectCountry3(RowBounds rowBounds);
三、插件定义:
package cn.edu.tju.config;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.util.Properties;
@Intercepts({
@Signature(type = Executor.class, method = "query", args = {
MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class
}),
@Signature(type = Executor.class, method = "query", args = {
MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class
})
})
public class MyPageInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
BoundSql boundSql = ms.getBoundSql(args[1]);
RowBounds rowBounds = (RowBounds) args[2];
String sql = boundSql.getSql();
sql += " limit ";
int offset = rowBounds.getOffset();
int limit = rowBounds.getLimit();
sql += (offset-1)*limit;
sql += ",";
sql += limit;
System.out.println(sql);
BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), sql,
boundSql.getParameterMappings(), boundSql.getParameterObject());
Executor executor = (Executor) invocation.getTarget();
return executor.query(ms, args[1], (RowBounds) args[2], (ResultHandler) args[3], null, newBoundSql);
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target,this);
}
@Override
public void setProperties(Properties properties) {
}
}
四、插件注册:
五、查询:
package cn.edu.tju.test;
import cn.edu.tju.domain.Country;
import cn.edu.tju.mapper.PersonMapper;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.util.List;
public class MyBatisTest11 {
public static void main(String[] args) throws IOException {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(
Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
List countries = sqlSession.getMapper(PersonMapper.class)
.selectCountry3(new RowBounds(1, 2));
System.out.println(countries.size());
System.out.println(countries);
}
}