0

When I set the following property in log4j.properties,

log4j.logger.package.mapper=DEBUG

MyBatis will delegate the job to log4jand log4j will print the WHOLE SQL statements in the log. Is there a way to just log the names of the SQL statements (id in XML which matches the mapper function name in JAVA if done with annotations)?

Ex. my select query in mapper is like this, if done through XML:

<select id="selectPerson" parameterType="int" ....

then I just want selectPerson to be logged. Currently it is being logged but it also includes the SQL statemenets with all parameter values. I just want to hide the actual SQL queries from the log.

1 Answer 1

3

MyBatis' logging implementation does not have an option to hide SQL, however, it would be possible to achieve it using a custom interceptor.
Assuming you are using the latest version of MyBatis, here is an example implementation.

package pkg;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;

@Intercepts({
  @Signature(
      type = Executor.class, 
      method = "update", 
      args = { MappedStatement.class, Object.class }),
  @Signature(
      type = Executor.class, 
      method = "query", 
      args = { MappedStatement.class, Object.class,
        RowBounds.class, ResultHandler.class })
})
public class LogStatementIdInterceptor implements Interceptor {
  private static final Logger logger = Logger.getLogger(LogStatementInterceptor.class);
  @Override
  public Object intercept(Invocation invocation) throws Throwable {
    MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
    logger.debug(ms.getId());
    return invocation.proceed();
  }
}

To register the interceptor, add the following entry to the XML config file.

<plugins>
  <plugin interceptor="pkg.LogStatementIdInterceptor" />
</plugins>

With Java config, pass an instance of the interceptor to org.apache.ibatis.session.Configuration#addInterceptor().

And in the log4j.properties ...

log4j.logger.pkg.LogStatementIdInterceptor=DEBUG
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.