mybatis中分页插件的使用
1、@Intercepts({@Signature(type=StatementHandler.class,method="prepare",args={Connection.class})})public class PagePlugin implements Interceptor { private static String dialect = ""; //数据库方言 private static String pageSqlId = ""; //mapper.xml中需要拦截的ID(正则匹配) public Object intercept(Invocation ivk) throws Throwable { // TODO Auto-generated method stub if(ivk.getTarget() instanceof RoutingStatementHandler){ RoutingStatementHandler statementHandler = (RoutingStatementHandler)ivk.getTarget(); BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler, "delegate"); MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate, "mappedStatement");
2、if(mappedStatement.getId().matches(pageSqlId)){ //拦截需要分页的SQLBoundSql boundSql = delegate.getBoundSql();Object parameterObject = boundSql.getParameterObject();//分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空if(parameterObject==null){throw new NullPointerException("parameterObject尚未实例化!");}
3、else{Connection connection = (Connection) ivk.getArgs()[0];String sql = boundSql.getSql();//String countSql = "select count(0) from (" + sql+ ") as tmp_count"; //记录统计String fhsql = sql;String countSql = "select count(0) from (" + fhsql+ ") tmp_count"; //记录统计 == oracle 加 as 报错(SQL command not properly ended)PreparedStatement countStmt = connection.prepareStatement(countSql);