恩,先将就着看看,注释有时间补上,说实话写时间有点久了我自己有点看不懂了。。。。
@Intercepts({@Signature(type=StatementHandler.class, args = {Connection.class}, method = "prepare")})
public class PageInterceptor implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler=(StatementHandler)invocation.getTarget();
MetaObject metaObject=MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY,SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,new DefaultReflectorFactory());
MappedStatement statement=(MappedStatement)metaObject.getValue("delegate.mappedStatement");
String id=statement.getId();
if(id.matches(".+ByPage$")){//处理所有ByPage结尾的方法
BoundSql boundSql = statementHandler.getBoundSql();
String sql=boundSql.getSql();
String countSql="select count(*) from ("+sql+") a";
Connection connection=(Connection)invocation.getArgs()[0];
PreparedStatement prepareStatement = connection.prepareStatement(countSql);
ParameterHandler parameterHandler = (ParameterHandler)metaObject.getValue("delegate.parameterHandler");
parameterHandler.setParameters(prepareStatement);
ResultSet rs=prepareStatement.executeQuery();
Page page=null;
Object obj = boundSql.getParameterObject();
if(obj instanceof Map){
Map map=(Map)obj;
page=(Page)map.get("page");
}
if(rs.next()){
page.setTotalNumber(rs.getInt(1));
}
String pageSql=sql+" limit "+page.getDbIndex()+","+page.getPageNumber();
metaObject.setValue("delegate.boundSql.sql",pageSql);
}
return invocation.proceed();
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public void setProperties(Properties arg0) {
// TODO Auto-generated method stub
}
}