plugins

MyBatis allows you to intercept calls to at certain points within the execution of a mapped statement. By default, MyBatis allows plug-ins to intercept method calls of:

  • Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  • ParameterHandler (getParameterObject, setParameters)
  • ResultSetHandler (handleResultSets, handleOutputParameters)
  • StatementHandler (prepare, parameterize, batch, update, query)

The details of these classes methods can be discovered by looking at the full method signature of each, and the source code which is available with each MyBatis release. You should understand the behaviour of the method you’re overriding, assuming you’re doing something more than just monitoring calls. If you attempt to modify or override the behaviour of a given method, you’re likely to break the core of MyBatis. These are low level classes and methods, so use plug-ins with caution.

Using plug-ins is pretty simple given the power they provide. Simply implement the Interceptor interface, being sure to specify the signatures you want to intercept.

  1. // ExamplePlugin.java
  2. @Intercepts({@Signature(
  3. type= Executor.class,
  4. method = "update",
  5. args = {MappedStatement.class,Object.class})})
  6. public class ExamplePlugin implements Interceptor {
  7. private Properties properties = new Properties();
  8. @Override
  9. public Object intercept(Invocation invocation) throws Throwable {
  10. // implement pre-processing if needed
  11. Object returnObject = invocation.proceed();
  12. // implement post-processing if needed
  13. return returnObject;
  14. }
  15. @Override
  16. public void setProperties(Properties properties) {
  17. this.properties = properties;
  18. }
  19. }
  1. <!-- mybatis-config.xml -->
  2. <plugins>
  3. <plugin interceptor="org.mybatis.example.ExamplePlugin">
  4. <property name="someProperty" value="100"/>
  5. </plugin>
  6. </plugins>

The plug-in above will intercept all calls to the “update” method on the Executor instance, which is an internal object responsible for the low-level execution of mapped statements.

NOTE Overriding the Configuration Class

In addition to modifying core MyBatis behaviour with plugins, you can also override the Configuration class entirely. Simply extend it and override any methods inside, and pass it into the call to the SqlSessionFactoryBuilder.build(myConfig) method. Again though, this could have a severe impact on the behaviour of MyBatis, so use caution.