mybatis 拦截器如何通过Invocation获取完整sql
时间: 2024-05-07 19:17:07 浏览: 139
通过Mybatis拦截器自动定位慢SQL并记录日志
语句并进行修改?
Mybatis拦截器可以通过Invocation对象获取完整的SQL语句并进行修改。在拦截器的intercept方法中,可以获取到方法调用的相关信息,包括Mapper接口、方法名、方法参数等。通过这些信息,可以获取到BoundSql对象,它包含了原始的SQL语句和参数信息。可以通过BoundSql对象获取完整的SQL语句并进行修改,然后再将修改后的SQL语句设置回BoundSql对象即可。
具体实现可以参考以下代码:
```
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement mappedStatement = (MappedStatement) args[0];
Object parameterObject = args[1];
BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
String sql = boundSql.getSql();
// 在这里对SQL语句进行修改
String newSql = modifySql(sql);
// 将修改后的SQL语句重新设置回BoundSql对象中
BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), newSql, boundSql.getParameterMappings(), parameterObject);
MappedStatement newMappedStatement = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
args[0] = newMappedStatement;
return invocation.proceed();
}
private String modifySql(String sql) {
// 在这里可以对SQL语句进行修改,例如添加分页的limit条件
return "select * from (" + sql + ") limit 0, 10";
}
private MappedStatement copyFromMappedStatement(MappedStatement mappedStatement, SqlSource newSqlSource) {
MappedStatement.Builder builder = new MappedStatement.Builder(mappedStatement.getConfiguration(), mappedStatement.getId(), newSqlSource, mappedStatement.getSqlCommandType());
builder.resource(mappedStatement.getResource());
builder.fetchSize(mappedStatement.getFetchSize());
builder.statementType(mappedStatement.getStatementType());
builder.keyGenerator(mappedStatement.getKeyGenerator());
builder.keyProperty(mappedStatement.getKeyProperty());
builder.timeout(mappedStatement.getTimeout());
builder.parameterMap(mappedStatement.getParameterMap());
builder.resultMaps(mappedStatement.getResultMaps());
builder.cache(mappedStatement.getCache());
builder.useCache(mappedStatement.isUseCache());
return builder.build();
}
```
阅读全文