MyBatis Tutorial-MyBatis plugin (Plugins) development

Source: Internet
Author: User
Tags config prepare xmlns

MyBatis allows you to intercept calls at a point during the execution of a mapped statement. By default, MyBatis allows the use of plug-ins to intercept method calls including: Executor (update, query, Flushstatements, Commit, rollback,
Gettransaction, Close, isClosed) Parameterhandler (Getparameterobject, setparameters) Resultsethandler ( Handleresultsets, Handleoutputparameters) Statementhandler (Prepare, parameterize, batch, update, query)

The details of the methods in these classes can be found by looking at the signature of each method, or by looking directly at the source code in the MyBatis's release package. Assuming you want to do more than just call the monitoring method, you should be well aware of the behavior of the method being rewritten. Because if you are trying to modify or rewrite the behavior of an existing method, you are likely to be destroying the core module of MyBatis. These are the lower classes and methods, so be careful when using plugins.

With the powerful mechanism provided by MyBatis, the use of plug-ins is very simple, just implement the Interceptor interface and specify the method signature you want to intercept. Custom Plugins Requirements:

Write down all SQL executed by MyBatis. Code Implementation

By intercepting the prepare method in the MyBatis org.apache.ibatis.executor.statement.StatementHandler .

The Prepare method signature is as follows:

Statement Prepare (Connection Connection, Integer transactiontimeout)
      throws SQLException;

To customize a class to implement the Org.apache.ibatis.pluginInterceptor interface, the code is as follows:

Package com.bytebeats.mybatis3.interceptor;
Import Org.apache.ibatis.executor.statement.StatementHandler;
Import ORG.APACHE.IBATIS.MAPPING.BOUNDSQL;
Import org.apache.ibatis.plugin.*;
Import Org.slf4j.Logger;

Import Org.slf4j.LoggerFactory;
Import java.sql.Connection;

Import java.util.Properties; /** * ${description} * * @author Ricky Fung * @date 2017-02-17 11:52 */@Intercepts ({@Signature (type = Statementhand Ler.class, method = "Prepare", args = {connection.class, integer.class})}) public class Sqlstatsinterceptor implements I

    Nterceptor {private final Logger Logger = Loggerfactory.getlogger (This.getclass ());  @Override public Object intercept (invocation invocation) throws Throwable {Statementhandler Statementhandler
        = (Statementhandler) invocation.gettarget ();
        Boundsql boundsql = Statementhandler.getboundsql ();
        String sql = Boundsql.getsql ();
        Logger.info ("MyBatis Intercept sql:{}", SQL);
  return Invocation.proceed ();  } @Override public Object plugin (object target) {return Plugin.wrap (target, this); } @Override public void SetProperties (properties properties) {String dialect = Properties.getproperty ("D
        Ialect ");
    Logger.info ("MyBatis Intercept dialect:{}", dialect);
 }
}

Such a plug-in will be developed, the next need to add the plugins node in the Mybatis-config.xml file, the complete configuration is as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "
        http://mybatis.org/dtd/mybatis-3-config.dtd" >

<configuration>

    <plugins>
        <plugin interceptor= " Com.bytebeats.mybatis3.interceptor.SQLStatsInterceptor ">
            <property name=" dialect "value=" MySQL "/>
        </plugin>
    </plugins>
</configuration>

Spring-mybatis.xml

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:tx= "Http://www.springframework.org/schema/tx" Xmlns:co
       ntext= "Http://www.springframework.org/schema/context" xmlns:util= "Http://www.springframework.org/schema/util" xsi:schemalocation= "Http://www.springframework.org/schema/beans HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/BEANS/SPR Ing-beans.xsd Http://www.springframework.org/schema/util http://www.springframework.org/schema/util/ Spring-util.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/
    Spring-tx.xsd "> <util:properties id=" db "location=" Classpath:db.properties "/> <!--configuration data source <bean name= "Parentdatasource" abstract= "true" class= "com.alibaba.drUid.pool.DruidDataSource "> <!--Initialize connection size--<property name=" InitialSize "value=" 1 "/>
        <!--connection pool maximum number of connections--<property name= "maxactive" value= "/>" <!--connection pool min free-- <property name= "Minidle" value= "/> <!--get connection maximum waiting time-<property name=" maxwait "Valu E= "30000"/> <property name= "validationquery" value= "Select 1"/> <property name= "Testonborrow  "Value=" true "/> <property name=" Testonreturn "value=" true "/> <property name=" Testwhileidle " Value= "true"/> <!--configuration interval to detect the idle connection that needs to be closed, in milliseconds--and <property name= Timebetweenevictionr Unsmillis "value=" 60000 "/> <!--Configure the minimum lifetime of a connection in the pool, in milliseconds--and <property name= ' Minevictableidleti Memillis "value=" 25200000 "/> <!--open removeabandoned function--<property name=" removeabandoned "va
       Lue= "true"/> <!--1800 seconds, that is 30 minutes--<property name= "removeabandonedtimeout" value= "1800"/> <!--off Aban Ded output error log when connected--<property name= "logabandoned" value= "true"/> <!--monitoring database--<p Roperty name= "Filters" value= "Mergestat"/> </bean> <!--trade data source--<bean name= ' trade ' in It-method= "Init" destroy-method= "Close" parent= "Parentdatasource" > <property name= "driverclassname" value= "# {db[' trade.jdbc.driverClassName '} "/> <property name=" url "value=" #{db[' Trade.jdbc.url ']} "/> &L T;property name= "username" value= "#{db[' Trade.jdbc.username ']}"/> <property name= "password" value= "#{db[' tr Ade.jdbc.password ']} "/> </bean> <!--admin data Source--<bean name=" admin "init-method=" Init "de Stroy-method= "Close" parent= "Parentdatasource" > <property name= "driverclassname" value= "#{db[" Admin.jdbc.dri
 Verclassname ']} "/>       <property name= "url" value= "#{db[' Admin.jdbc.url ']}"/> <property name= "username" value= "#{db[" adm In.jdbc.username ']} "/> <property name=" password "value=" #{db[' Admin.jdbc.password ']} "/> &LT;/BEAN&G

    T <!--trade MyBatis config--> <bean id= "tradesqlsessionfactory" class= " Org.mybatis.spring.SqlSessionFactoryBean "> <property name=" dataSource "ref=" trade "/> <propert Y name= "mapperlocations" value= "Classpath*:mapper/trade/*mapper.xml"/> <property name= "ConfigLocation" Valu E= "Classpath:mybatis-config.xml"/> <property name= "typealiasespackage" value= "Com.bytebeats.mybatis3.domain . Trade "/> </bean> <bean class=" Org.mybatis.spring.mapper.MapperScannerConfigurer "> &LT;PR Operty name= "Basepackage" value= "Com.bytebeats.mybatis3.mapper.trade"/> <property name= "Sqlsessionfactorybe Anname "value=" Tradesqlsessionfactory "/> </bean> <!--admin MyBatis config--> <bean id= "adminsqlsessionfactory" class= "Org.mybatis.spring.SqlSessio Nfactorybean "> <property name=" dataSource "ref=" admin "/> <property name=" Mapperlocations "Val Ue= "Classpath*:mapper/admin/*mapper.xml"/> <property name= "typealiasespackage" value= "Com.bytebeats.mybatis
        3.domain.admin "/> </bean> <bean class=" Org.mybatis.spring.mapper.MapperScannerConfigurer "> <property name= "Basepackage" value= "Com.bytebeats.mybatis3.mapper.admin"/> <property name= "Sqlsessionfa Ctorybeanname "value=" Adminsqlsessionfactory "/> </bean> <!--configuration Transaction--<bean id=" Transactio Nmanager "class=" Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" Datasou Rce "ref=" trade "/> </bean> <tx:annotation-driven transaction-manager=" TransactionManager "/> &lt ;/beans>
maven Dependency
    <properties> <java.version>1.7</java.version> <spring.version>4.2.7.release&lt ;/spring.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </prope Rties> <dependencies> <!--spring--<dependency> <groupid>or G.springframework</groupid> <artifactId>spring-core</artifactId> <version> ${spring.version}</version> <exclusions> <exclusion> &lt
                ;artifactid>commons-logging</artifactid> <groupId>commons-logging</groupId>
            </exclusion> </exclusions> </dependency> <dependency>
            <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.s Pringframework</groupid> <artifactId>spring-context</artifactId> <version> ${spring.version}</version> </dependency> <dependency> <groupid>org.sp Ringframework</groupid> <artifactId>spring-context-support</artifactId> <vers ion>${spring.version}</version> </dependency> <dependency> <groupid&gt ;org.springframework</groupid> <artifactId>spring-webmvc</artifactId> <versio n>${spring.version}</version> </dependency> <dependency> <groupid>o Rg.springframework</groupid> <artifactId>spring-tx</artifactId> <version>$ {Spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid > <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version 
            > </dependency> <dependency> <groupId>org.springframework</groupId> 
        <artifactId>spring-test</artifactId> <version>${spring.version}</version>
            </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </d
            ependency> <!--db--> <dependency> <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version>

   </dependency>     <dependency> <groupId>com.alibaba</groupId> <artifactid>druid</art
        Ifactid> <version>1.0.25</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactid>mybatis</
             artifactid> <version>3.4.1</version> </dependency> <dependency>  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.