问题描述
- mybatis拦截器分页问题。intercept有时候不执行
-
我在SSM工程中使用mybatis拦截器做分页,但是拦截器的intercept有时候执行有时候不执行,不知道为什么,程序员没有没有经验呢?谢谢赐教代码:
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class })})
public class PageInterceptor implements Interceptor {private static String sqlId = "";
private static String dialect = "";
public Object intercept(Invocation inv) throws Throwable {
System.out.println("到了");
RoutingStatementHandler handler = (RoutingStatementHandler) inv.getTarget();
StatementHandler delegate = (StatementHandler)ReflectionUtils.getFieldValue(handler, "delegate");
MappedStatement mappedStatement = (MappedStatement) ReflectionUtils.getFieldValue(delegate, "mappedStatement");if(mappedStatement.getId().matches(sqlId)) { //只拦截id包含pages的SQL
BoundSql bound = delegate.getBoundSql();//获得当前绑定Sql的参数对象
Object object = bound.getParameterObject();
if(object == null) {
return inv.proceed();
}
if(object instanceof PageEntity<?>) {
PageEntity<?> page = (PageEntity<?>)object;
String sql = bound.getSql();String pageSql = getPageSql(sql, page);
ReflectionUtils.setFieldValue(bound, "sql", pageSql);
}
}
return inv.proceed();
}public String getPageSql(String sql, PageEntity<?> page) {
//此处省略SQL拼接代码
return pageSql.toString();
}public Object plugin(Object arg0) {
return Plugin.wrap(arg0, this);
}public void setProperties(Properties property) {
sqlId = property.getProperty("sqlId"); //".*Pages*.*"
dialect = property.getProperty("dialect"); //"oracle"
}}
配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<mappers> <mapper resource="com/cifpay/user/entity/User.sqlMap.xml" /> <mapper resource="com/cifpay/role/entity/Role.sqlMap.xml" /> <mapper resource="com/cifpay/menu/entity/Menu.sqlMap.xml"/> <mapper resource="com/cifpay/role/entity/RoleMenuMap.sqlMap.xml"/> <mapper resource="com/cifpay/role/entity/UserRoleMap.sqlMap.xml"/> </mappers>