Springboot Series Seven: Springboot Integrated MyBatis (Configuration Druid Data source, configuration MyBatis, transaction control, druid monitoring)

Source: Internet
Author: User
Tags dname i18n

1, Concept: springboot integration MyBatis

2. Background

Springboot get the final effect is a simplification to the extreme web development, but as long as the web development involved, it is absolutely impossible to lack of data layer operation, all development must uphold the principle of MVC design pattern, MVC business layer is not few, the data layer will always be tied to the business layer, Since the data layer to operate, then certainly the first choice must be MyBatis, because MyBatis integration processing, especially with the Spring integration can directly avoid the writing of the DAO layer, while the VO class is also the cleanest, which is definitely more than the other ormapping components Convenient.

2.1. Configuring the Druid Data source

This database connection pool configuration is provided by Ali, and because of its high performance, but also has a good monitoring, in the actual development has begun to be widely used.

1. First write a database creation script:

DROP datbase IF EXISTS study; CREATE datbase study CHARACTER SET UTF8; Use study; CREATE TABLE Dept (    deptno        BIGINT        auto_increment,    dname        VARCHAR (),    CONSTRAINT Pk_deptno PRIMARY KEY (DEPTNO)), insert INTO dept (dname) VALUES (' Development Department '), insert INTO dept (dname) VALUES (' Finance Department '); INSERT INTO Dept (DNA Me) VALUES (' marketing Department '), insert INTO dept (dname) VALUES (' logistics '), insert INTO dept (dname) VALUES (' PR ');

2, then to druid the configuration of the data source, if you want to use Druid data source, then you must first modify the Pom.xml configuration file, introduce the following package:

             <dependency>                <groupId>mysql</groupId>                <artifactid>mysql-connector-java</ artifactid>                <version>5.0.4</version>            </dependency>            <dependency>                <groupId>com.alibaba</groupId>                <artifactId>druid</artifactId>                <version> 1.0.31</version>            </dependency>

3, if you want to do the integration of data source processing, directly modify the APPLICATION.YML configuration file can:

Server:  port:80spring:  messages:    basename:i18n/messages,i18n/pages  DataSource:    type: Com.alibaba.druid.pool.DruidDataSource    # Configure the type of operation for the data source you are currently using    Driver-class-name:org.gjt.mm.mysql.driver      # Configure the MySQL driver class    url:jdbc:mysql://localhost:3306/study           # Database connection address    username:root                                  # Database user name    password:mysqladmin                            # database connection password    DBCP2:                                          # Database Connection pool configuration      min-idle:5                                   # Minimum number of maintenance connections for the database connection pool          Initial-size:5                               # Initialize the number of connections provided      Max-total:5                                  # Maximum number of connections      max-wait-millis:200                          # Maximum timeout time to wait for a connection to get

4. If you need to perform JUnit code testing at this time, be sure to configure the MyBatis development package because only the MyBatis development package will change the Druid configuration database connection pool to the desired DataSource data source object.

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

5. Test if the current connection pool is available

Package Cn.study.microboot.test;import Javax.annotation.resource;import Javax.sql.datasource;import org.junit.Test ; Import Org.junit.runner.runwith;import Org.springframework.boot.test.context.springboottest;import Org.springframework.test.context.junit4.springjunit4classrunner;import Org.springframework.test.context.web.webappconfiguration;import cn.study.microboot.startspringbootmain;@ Springboottest (classes = startspringbootmain.class) @RunWith (Springjunit4classrunner.class) @ Webappconfigurationpublic class Testdatasource {    @Resource    private DataSource DataSource;    @Test public    void Testconnection () throws Exception {        System.out.println (this.datasource);    }}

The database connection can now be obtained, indicating that the current druid is configured correctly.

2.2, Configuration MyBatis

If you want to make MyBatis configuration, be sure to import the MyBatis development package that Spring-boot supports.

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

1, then to modify the application.yml configuration file, append mybatis related configuration items:

MyBatis:  config-location:classpath:mybatis/mybatis.cfg.xml    # mybatis configuration file where the path  type-aliases-package: Cn.study.microboot.vo            # Defines the alias of all operation classes package  mapper-locations:                                     # All Mapper mapping files  -classpath:mybatis/ Mapper/**/*.xml

2, the establishment of a Dept VO class:

Package Cn.study.microboot.vo;import java.io.Serializable, @SuppressWarnings ("Serial") public class Dept implements Serializable {    private Long deptno;    Private String dname;    Public Long Getdeptno () {        return deptno;    }    public void Setdeptno (Long deptno) {        this.deptno = deptno;    }    Public String Getdname () {        return dname;    }    public void Setdname (String dname) {        this.dname = dname;    }    @Override public    String toString () {        return "Dept [deptno=" + Deptno + ", dname=" + dname + "]";    }}

3. A mybatis/mybatis.cfg.xml configuration file is established in the Src/main/resources directory:

<?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>    <!--to mybatis the corresponding environment of the property definition--    <settings>    <!--turn on level two cache in this project--        <setting name= "cacheenabled" value= "true"/>    </settings></ Configuration>

4, Src/main/resources/mybatis under the establishment of a mapper subdirectory, and then within the definition of a cn/mldn/dept.xml configuration file:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >< Mapper namespace= "Cn.study.microboot.dao.IDeptDAO" >    <select id= "FindAll" resulttype= "Dept" >        SELECT deptno,dname from Dept;    </select></mapper>  

5, establish Ideptdao interface, note the package where the interface is located:

Package Cn.study.microboot.dao;import Java.util.list;import Org.apache.ibatis.annotations.mapper;import cn.study.microboot.vo.Dept; @Mapperpublic interface Ideptdao {public    list<dept> findAll ();}

When defining the DAO interface, it is necessary to write a "@Mapper" annotation at the interface declaration, otherwise your DAO interface and the *.xml Mapper file cannot be integrated because of the need to automatically generate the implementation subclass.

6, the establishment of a Ideptservice interface, as a service use:

Package Cn.study.microboot.service;import Java.util.list;import Cn.study.microboot.vo.dept;public interface Ideptservice {public    list<dept> List ();}
Package Cn.study.microboot.service.impl;import Java.util.list;import Javax.annotation.resource;import Org.springframework.stereotype.service;import Cn.study.microboot.dao.ideptdao;import Cn.study.microboot.service.ideptservice;import cn.study.microboot.vo.Dept; @Servicepublic class Deptserviceimpl Implements Ideptservice {    @Resource    private Ideptdao Deptdao;    @Override public    list<dept> List () {        return this.deptDAO.findAll ();    }}

7, the Code test class to write:

Package Cn.study.microboot.test;import Javax.annotation.resource;import Org.junit.test;import Org.junit.runner.runwith;import Org.springframework.boot.test.context.springboottest;import Org.springframework.test.context.junit4.springjunit4classrunner;import Org.springframework.test.context.web.webappconfiguration;import Cn.study.microboot.startspringbootmain;import Cn.study.microboot.service.IDeptService; @SpringBootTest (classes = startspringbootmain.class) @RunWith ( Springjunit4classrunner.class) @WebAppConfigurationpublic class Testdeptservice {    @Resource    private Ideptservice Deptservice;    @Test public    void Testlist () throws Exception {        System.out.println (this.deptService.list ());}    }

At this point the test passes, then Springboot and MyBatis can be successfully integrated into the project development, at this time the configuration is more than the previous use of Spring + MyBatis Direct configuration simple N multiple times.

2.3. Transaction control

1, modify the Ideptservice interface, append a read-only transaction control:

Package Cn.study.microboot.service;import Java.util.list;import Org.springframework.transaction.annotation.propagation;import Org.springframework.transaction.annotation.transactional;import Cn.study.microboot.vo.dept;public Interface Ideptservice {    @Transactional (readOnly = true) public    list<dept> List ();}

A read-only transaction operation is configured at this point, which means that the business method can only operate in a read mode.

2, but now you have configured a note does not indicate that the transaction is currently reasonably supported, if you want to enable the transaction, you also need to append a new annotation configuration on the program startup class:

Package Cn.study.microboot;import Org.springframework.boot.springapplication;import Org.springframework.boot.autoconfigure.springbootapplication;import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication    // Start the Springboot program, and then scan the @enabletransactionmanagementpublic class Startspringbootmain {public    static void main ( String[] args) throws Exception {        springapplication.run (startspringbootmain.class, args);}    }

3, if you want to better observe the problem of the transaction, the simplest way is to write a data increase operation, and then set the read-only configuration for this business method.

· Modify the Ideptdao interface to append a new method:

Package Cn.study.microboot.dao;import Java.util.list;import Org.apache.ibatis.annotations.mapper;import cn.study.microboot.vo.Dept; @Mapperpublic interface Ideptdao {public    list<dept> findAll ();    public boolean docreate (Dept vo);

· Modify the Dept.xml configuration file to append a method to the implementation of the SQL statement:

<insert id= "Docreate" parametertype= "Dept" >        insert INTO Dept (dname) VALUES (#{dname});</insert>

· There is a business method appended to the Ideptservice interface:

@Transactional ((readOnly = True) public    boolean add (Dept vo);

· To write a test method:

    @Test public    void Testadd () throws Exception {        Dept Dept = new Dept ();        Dept.setdname ("testing Department");        System.out.println (This.deptService.add (dept));    }

This will cause an error

4, if in the actual work, for the update operation should be mandatory to start a transaction control to:

@Transactional (propagation=propagation.required) Public boolean add (Dept vo);

It should be clear at this point that the action method should start a configuration item that has a transaction.

5, in the use of spring+mybatis inside should consider the information display problem, so it is recommended to use the Logback log component to configure the log information;

· Copy the Logback.xml configuration file into the Src/main/resources directory;

<?xml version= "1.0" encoding= "UTF-8"? ><configuration scan= "true" > <property name= "APP" value= "${ Project.artifactid} "/> <property name=" log_home "value="/data/www/log/${app} "/> <appender name=" CONSOL E "class=" Ch.qos.logback.core.ConsoleAppender "> <encoder> <pattern>%d{yy-mm-dd.hh:mm:ss.s SS} [%-16t]%-5p%-22c{0}%x{serviceid}-%m%n</pattern> </encoder> </appender> <appende R name= "DETAIL" class= "Ch.qos.logback.core.rolling.RollingFileAppender" additivity= "false" > <file>$ {log_home}/${app}_detail.log</file> <encoder> <pattern>%d{yy-mm-dd.hh:mm:ss. SSS} [%-16t]%-5p%-22c{0}%x{serviceid}-%m%n</pattern> </encoder> <rollingpolicy class= "ch . qos.logback.core.rolling.TimeBasedRollingPolicy "> <filenamepattern>${log_home}/${app}_detail.log.%d{y Yyymmdd}</filenamepattern> &Lt;/rollingpolicy> </appender> <appender name= "ACCESS" class= "Ch.qos.logback.core.rolling.RollingF            Ileappender "additivity=" false "> <File>${LOG_HOME}/${APP}_access.log</File> <encoder> <pattern>%d{yy-mm-dd.hh:mm:ss. sss};%x{serviceid};%m%n</pattern> </encoder> <rollingpolicy class= "Ch.qos.logback.core.rollin G.timebasedrollingpolicy "> <filenamepattern>${log_home}/${app}_access.log.%d{yyyymmdd}</filenamepat tern> </rollingPolicy> </appender> <logger name= "ACCESS" > <appender-ref ref= "A Ccess "/> </logger> <logger name=" druid.sql.Statement "level=" DEBUG "/> <logger name=" Cn.study. Microboot.dao "level=" TRACE "/> <root level=" INFO "> <appender-ref ref=" DETAIL "/> <appe Nder-ref ref= "CONSOLE"/> </root></configuration>

· In the project to introduce Logback dependent program files:

         <dependency>            <groupId>ch.qos.logback</groupId>            <artifactid>logback-core</ Artifactid>        </dependency>

· Under normal circumstances, the output of log information in MyBatis must set its corresponding namespace and append the following information in Logback.xml:

<logger name= "Cn.study.microboot.dao" level= "TRACE"/>

2.4, Druid Monitoring

The main reason why the Druid database connection pool is so widely used is that it can provide performance monitoring directly. So this time for a performance monitoring configuration for the Druid configuration that is currently implemented.

1, if you want to perform DRUID performance monitoring operations, you need to do some basic configuration, such as: Whether you access the IP address is a whitelist.

Package Cn.study.microboot.config;import Javax.sql.datasource;import Org.springframework.boot.context.properties.configurationproperties;import Org.springframework.boot.web.servlet.filterregistrationbean;import Org.springframework.boot.web.servlet.servletregistrationbean;import Org.springframework.context.annotation.Bean ; Import Org.springframework.context.annotation.configuration;import Com.alibaba.druid.pool.DruidDataSource; Import Com.alibaba.druid.support.http.statviewservlet;import com.alibaba.druid.support.http.webstatfilter;@        Configurationpublic class Druidconfig {@Bean public Servletregistrationbean Druidservlet () {//primary implementation of Web monitoring configuration processing Servletregistrationbean Servletregistrationbean = new Servletregistrationbean (new Statviewservlet (), "/ druid/* ");  The configuration processing operation for druid monitoring is now Servletregistrationbean.addinitparameter ("Allow", "127.0.0.1,192.168.1.159"); Whitelist Servletregistrationbean.addinitparameter ("Deny", "192.168.1.200"); Black NameSingle Servletregistrationbean.addinitparameter ("Loginusername", "Studyjava"); User name Servletregistrationbean.addinitparameter ("Loginpassword", "Hello"); Password Servletregistrationbean.addinitparameter ("Resetenable", "false");    Whether the data source can be reset return servletregistrationbean; } @Bean Public Filterregistrationbean Filterregistrationbean () {Filterregistrationbean Filterregistrationbea        n = new Filterregistrationbean ();        Filterregistrationbean.setfilter (New Webstatfilter ()); Filterregistrationbean.addurlpatterns ("/*");        All requests are monitored and processed filterregistrationbean.addinitparameter ("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");    return Filterregistrationbean; } @Bean @ConfigurationProperties (prefix = "Spring.datasource") public datasource Druiddatasource () {retur    N New Druiddatasource (); }}

2, in order to better explain the problem, it is recommended to establish a controller for business layer calls;

Package Cn.study.microboot.controller;import Javax.annotation.resource;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.bind.annotation.restcontroller;import Cn.study.microboot.service.ideptservice;import Cn.study.microboot.util.controller.AbstractBaseController, @RestControllerpublic class Deptcontroller extends Abstractbasecontroller {    @Resource    private ideptservice deptservice;    @RequestMapping (value = "/list", method = requestmethod.get) public    Object list () {//through model can implement content delivery        return th Is.deptService.list ();     }}

3, if you want to monitor also need to open a filter configuration, and this filter configuration is required to open through the application.yml file configuration;

Spring:  messages:    basename:i18n/messages,i18n/pages  DataSource:    type: Com.alibaba.druid.pool.DruidDataSource    # Configure the type of operation for the data source you are currently using    Driver-class-name:org.gjt.mm.mysql.driver      # Configure the MySQL driver class    url:jdbc:mysql://localhost:3306/study           # Database connection address    username:root                                  # Database user name    password:mysqladmin                            # database connection password    filters:stat,wall,log4j    dbcp2:                                          # Database Connection pool configuration      Min-idle:5                                   # Minimum number of holdout connections for database connection pool          initial-size:5                               # Initialize the number of connections provided      Max-total:5                                  # Maximum number      of connections max-wait-millis:200                          # The maximum timeout time to wait for a connection to get

Start the project, enter HTTP://LOCALHOST/DRUID in the browser address bar, then enter the username Studyjava, the password hello will be able to see the monitoring page

Springboot Series Seven: Springboot Integrated MyBatis (Configuration Druid Data source, configuration MyBatis, transaction control, druid monitoring)

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.