A, mybatis plug-in function can intercept targets
Two, Mybatis plug-in functionality access procedure
1, implement the interface: org.apache.ibatis.plugin.Interceptor
2, the interface implementation class and method for describing an annotation @Intercepts and @Signature added as necessary to intercept the class
@Documented @Retention (RetentionPolicy.RUNTIME) @Target (ElementType.TYPE) public @ interface Intercepts { the Signature [] value (); // Method to intercept the description } @Documented @Retention (RetentionPolicy.RUNTIME) @Target (the ElementType .TYPE) public @ interface the Signature { class type () <?>; // described to block class (interface) String method (); // to intercept the name of the class [] args () <?>; / / type to intercept parameter list of the method name }
3, to achieve the object class Interceptor injected into the Configuration of interceptorChain
Third, write a print plug case currently executing sql statement
1, analysis
Based on the implementation plan mybatis, StatementHandler there is a method BoundSql getBoundSql (), which is called as soon as the connection to the database application, and when binding parameters, get the sql statement from within sql statement.
Therefore, the need for plug-ins StatementHandler to intercept and obtain sql statement from the returned results in its execution getBoundSql statement and print
2, Notes
Premise mybatis use of plug-in function is to mybatis framework is very familiar with.
3, case
@Intercepts(value = {@Signature(type = StatementHandler.class,method = "prepare",args = {Connection.class,Integer.class})}) public class SqlPrintInterceptor implements Interceptor { /** * 决定那个对象需要进行代理拦截 * @param target * @return */ @Override public Object plugin(Object target) { if(target instanceof StatementHandler){ return Plugin.wrap(target, this); } return target; } / ** * perform logic reinforcing agent * @param Invocation * @return * @throws the Throwable * / @Override public Object Intercept (the Invocation Invocation) throws the Throwable { Object obj = invocation.proceed (); RoutingStatementHandler Handler = (RoutingStatementHandler) invocation.getTarget (); System.out.println ( "current SQL do = [" + handler.getBoundSql () getSql () +. "]" ); return obj; } / ** * set the current proxy configuration * @param properties */ @Override public void setProperties(Properties properties) { } }
interceptorChain