Skip to content

Can I add arbitrary parameters using Interceptor? #3245

Closed
@aki-caffeine

Description

@aki-caffeine

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions