I created the following settings to add common parameters using Interceptor and reference them from SQL managed in xml.
【Interceptor】
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class }),
})
@Component
public class MybatisAddParamInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler stHandler = StatementHandler.class.cast(invocation.getTarget());
BoundSql boundSql = stHandler.getBoundSql();
boundSql.setAdditionalParameter("key1", "value1");
return invocation.proceed();
}
}
【mapper interface】
@Mapper
public interface MapperInterface {
int selectKey1(@Param("param") ParamObject param);
}
【xml】
<select id="selectKey1" resultType="int" parameterType="map">
SELECT
#{key1}
FROM table_A
</select>
However, although the system starts up successfully, the following error occurs when calling SQL.
Caused by: org.apache.ibatis.binding.BindingException: Parameter 'key1' not found. Available parameters are [param, param1]
at org.apache.ibatis.binding.MapperMethod$ParamMap.get(MapperMethod.java:210)
at org.apache.ibatis.reflection.wrapper.MapWrapper.get(MapWrapper.java:45)
at org.apache.ibatis.reflection.MetaObject.getValue(MetaObject.java:116)
at org.apache.ibatis.executor.BaseExecutor.createCacheKey(BaseExecutor.java:225)
at org.apache.ibatis.executor.CachingExecutor.createCacheKey(CachingExecutor.java:149)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:89)
I was hoping that parameter key1
would be registered using boundSql.setAdditionalParameter
, but it has not been registered. How should I modify the Interceptor to make these work properly?
Comment From: harawata
Hello @aki-caffeine ,
The official answer is "no". You might be able to achieve it using reflection, but we do not recommend it nor guarantee it will work in future version.
We do not use issues for questions. Please post your next question to one of the following.
- Stackoverflow : https://stackoverflow.com/questions/ask?tags=mybatis
- Mailing list : http://groups.google.com/group/mybatis-user
- Discussions : https://github.com/mybatis/mybatis-3/discussions
And when you ask, you should use more realistic example. The SQL in your example seems useless and it makes it difficult for other developers to provide useful advice.
SELECT #{key1} FROM table_A