mybatis插件的sql参数问题

米斯特_ 2020-01-02 10:17:11
最近在学习mybatis,想自己实现一个mybatis插件,但是遇到一些问题:
需求是这样的:我想把所有sql都动态添加一些查询条件,现在sql已经能够拼接出新的sql而且新增的查询条件的值也用‘?’进行填充(不想直接把值拼接到sql里面,想用预编译方式进行处理),但是参数却一直没能处理成功,想请教下哪个地方出问题了:

大致的代码如下:
@Intercepts(@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }))
public class QueryConditionHelper implements Interceptor {
@Override
public Object intercept(Invocation invocation) {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
//RowBounds rowBounds = (RowBounds) args[2];
BoundSql boundSql = ms.getBoundSql(parameter);
String sql = boundSql.getSql();
sql+=" AND TABLE.AAA=?";

List<ParameterMapping> parameterMappingList = new ArrayList<>(boundSql.getParameterMappings());
parameterMappingList.add(new ParameterMapping.Builder(ms.getConfiguration(), "AAA", Object.class).build());

BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), sql, parameterMappingList, boundSql.getParameterObject());

// 把新的查询放到statement里
SqlSource sqlSource = new StaticSqlSource(ms.getConfiguration(), sql, parameterMappingList);
MappedStatement newMs = copyFromMappedStatement(ms, sqlSource);

for (ParameterMapping mapping : newBoundSql.getParameterMappings()) {
String prop = mapping.getProperty();
if (boundSql.hasAdditionalParameter(prop)) {
newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
}
}
args[0] = newMs;
return invocation.proceed();
}

private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
builder.keyProperty(ms.getKeyProperties()[0]);
}
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.resultSetType(ms.getResultSetType());
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
return builder.build();
}



结果却一直报错: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'AAA' not found. Available parameters are [pdithuId, param1]
“pdithuId”是查询方法本来的业务参数,但是param1是什么回事?我应该怎么写才能达到我的需求?有懂的兄弟能够解答一下吗?
...全文
207 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
MavenTalk 2020-01-03
  • 打赏
  • 举报
回复
太抽象了,给个上下文吧

81,094

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧