Spring Boot Integration MyBatis

Source: Internet
Author: User
Spring Boot Integration MyBatis

Before integrating MyBatis, we first configure a Druid data source. Spring Boot Series

Getting Started with Spring Boot

Spring Boot Property Configuration and use

Spring Boot Integration MyBatis

Spring Boot static resource processing

Spring Boot-Configure sorting dependency techniques

Spring Boot-devtools introduces the spring Boot integration Druid

Druid has many configuration options, and using the spring Boot configuration file makes it easy to configure Druid.

In the APPLICATION.YML configuration file, write:

Spring:
    DataSource:
        name:test
        url:jdbc:mysql://192.168.16.137:3306/test
        username:root
        Password:
        # using Druid data source
        type:com.alibaba.druid.pool.DruidDataSource
        driver-class-name: Com.mysql.jdbc.Driver
        filters:stat
        maxactive:20
        initialsize:1
        maxwait:60000
        minidle:1
        timebetweenevictionrunsmillis:60000
        minevictableidletimemillis:300000
        validationquery:select ' X '
        testwhileidle:true
        testonborrow:false
        testonreturn:false
        poolpreparedstatements:true
        maxopenpreparedstatements:20

This can be done by Type:com.alibaba.druid.pool.DruidDataSource configuration. Spring Boot Integration MyBatis

There are two ways to Spring Boot integration MyBatis, and an easy way is to use the MyBatis official offer:

Mybatis-spring-boot-starter

Another way is to still use a similar mybatis-spring configuration, this way you need to write some code, but it is convenient to control the MyBatis configuration. First, Mybatis-spring-boot-starter way to add dependencies in Pom.xml:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId> mybatis-spring-boot-starter</artifactid>
    <version>1.0.0</version>
</dependency >

The Mybatis-spring-boot-starter dependency tree is as follows:

One of the 3.3.0 versions used by MyBatis is available through:
<mybatis.version>3.3.0</mybatis.version> property to modify the default version.
Mybatis-spring using version 1.2.3, you can pass:
<mybatis-spring.version>1.2.3</mybatis-spring.version> Modify the default version. to increase the configuration in Application.yml:

MyBatis: 
  mapperlocations:classpath:mapper/*.xml
  
In addition to the two common configurations listed above, there are:Mybatis.config:mybatis-config.xml configuration file path mybatis.typehandlerspackage: Scanning typehandlers Packages Mybatis.checkconfiglocation: Check that the configuration file exists Mybatis.executortype: Set execution mode (simple, reuse, BATCH), default to Simple second, mybatis-spring way

This approach is quite similar to the usual usage. Need to add MyBatis dependencies and mybatis-spring dependencies.

Then create a Mybatisconfig configuration class:

/** * MyBatis Base configuration * * @author Liuzh * @since 2015-12-19 10:11/@Configuration @EnableTransactionManagement public C

    Lass Mybatisconfig implements Transactionmanagementconfigurer {@Autowired DataSource DataSource; @Bean (name = "Sqlsessionfactory") public sqlsessionfactory Sqlsessionfactorybean () {Sqlsessionfactorybean bea
        n = new Sqlsessionfactorybean ();
        Bean.setdatasource (DataSource);

        Bean.settypealiasespackage ("Tk.mybatis.springboot.model");
        Paging plugin Pagehelper pagehelper = new Pagehelper ();
        Properties Properties = new properties ();
        Properties.setproperty ("reasonable", "true");
        Properties.setproperty ("Supportmethodsarguments", "true");
        Properties.setproperty ("Returnpageinfo", "check");
        Properties.setproperty ("params", "count=countsql");

        Pagehelper.setproperties (properties);

        Add plugin bean.setplugins (new interceptor[]{pagehelper}); Add XML Catalog ResOurcepatternresolver resolver = new Pathmatchingresourcepatternresolver ();
            try {bean.setmapperlocations (resolver.getresources ("Classpath:mapper/*.xml"));
        return Bean.getobject ();
            catch (Exception e) {e.printstacktrace ();
        throw new RuntimeException (e); @Bean public sqlsessiontemplate sqlsessiontemplate (sqlsessionfactory sqlsessionfactory) {return
    New Sqlsessiontemplate (sqlsessionfactory);  @Bean @Override public Platformtransactionmanager Annotationdriventransactionmanager () {return new
    Datasourcetransactionmanager (DataSource); }
}

The code above creates a sqlsessionfactory and a sqlsessiontemplate, adding @enabletransactionmanagement annotations to support annotation transactions, and returned a platformtransactionmanagerbean.

It should also be noted that there is no mapperscannerconfigurer in this configuration, and if we want to scan the MyBatis mapper interface, we need to configure this class, which we need to put in a separate class.

/**
 * MyBatis Scanning interface
 * 
 * @author liuzh
 * @since 2015-12-19 14:46
 /
@Configuration
//todo Note , because Mapperscannerconfigurer executes earlier, you must have the following annotation
@AutoConfigureAfter (mybatisconfig.class) Public
class Mybatismapperscannerconfig {

    @Bean public
    mapperscannerconfigurer mapperscannerconfigurer () {
        Mapperscannerconfigurer mapperscannerconfigurer = new Mapperscannerconfigurer ();
        Mapperscannerconfigurer.setsqlsessionfactorybeanname ("Sqlsessionfactory");
        Mapperscannerconfigurer.setbasepackage ("Tk.mybatis.springboot.mapper");
        Return Mapperscannerconfigurer
    }

}

This configuration must pay attention to @autoconfigureafter (Mybatisconfig.class), must have this configuration, otherwise there will be an exception. The reason is that this class executes earlier, because the sqlsessionfactory does not exist, subsequent execution error.

You can use MyBatis after you have done the above configuration. about paging Plug-ins and general Mapper integration

The paging plugin as an example of Plug-ins is available in the above code.

The General mapper configuration is the actual configuration of the mapperscannerconfigurer when the use of Tk.mybatis.spring.mapper.MapperScannerConfigurer can be configured to use properties. the Spring boot integrated MyBatis infrastructure Project

I uploaded it to GitHub. A second approach to integration projects, and integrated paging plug-ins and general Mapper, the project contains a simple configuration and operations, only as a reference.

Project Address: Https://github.com/abel533/MyBatis-Spring-Boot

Information about the paging plugin and general Mapper can be found by the address above.

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.