Hibernate / MyBatis Interview questions
What is a plugin/interceptor in MyBatis, and how do you write one?
A MyBatis plugin is a custom interceptor that hooks into one of four specific internal interfaces — Executor, ParameterHandler, ResultSetHandler, or StatementHandler — letting a developer intercept and modify behavior at a specific stage of the query execution pipeline, such as logging every executed SQL statement or automatically injecting pagination parameters.
@Intercepts({ @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}) }) public class SqlLoggingInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { long start = System.currentTimeMillis(); Object result = invocation.proceed(); System.out.println("Query took " + (System.currentTimeMillis() - start) + "ms"); return result; } }
The @Intercepts/@Signature annotations declare exactly which method, on which interface, this plugin should wrap; inside intercept(), calling invocation.proceed() continues to the original, un-intercepted behavior, with the interceptor free to run logic before and after that call — timing it, logging it, or even modifying arguments and the returned result.
Once implemented, a plugin is registered globally in mybatis-config.xml (or as a Spring bean, in a Spring Boot application), after which it applies to every matching method call across the entire application; because plugins operate at such a low, central level in MyBatis's execution pipeline, they're commonly used for cross-cutting concerns like SQL performance logging, automatic pagination, data masking, or auditing, rather than business-logic-specific behavior that belongs elsewhere in the application.
More Related questions...