OpenWrite version:

Welcome to my GitHub

Github.com/zq2599/blog…

Content: all original article classification summary and supporting source code, involving Java, Docker, Kubernetes, DevOPS, etc.;

This article is “MyBatis primary combat” series of the third, we will combat springboot, MyBatis, DRUid integration, and verification;

About the druid

  1. Druid is a database connection pool and provides powerful monitoring and extension capabilities.
  2. Official GitHub address: github.com/alibaba/dru…
  3. This integration uses the official DurID starter named druid-spring-boot-starter whose version is 1.1.17. The druid version is 1.1.17

This paper gives an overview of

This article consists of the following contents:

  1. New SpringBoot project with detailed integration with Druid
  2. Write and execute unit test code and avoid a problem with integration Druid;
  3. Start the Springboot application and verify that the basic function is normal by Swagger.
  4. Verify that the Druid connection pool is used by the breakpoint;
  5. Experience the monitoring page provided by Druid

Download the source code

  1. If you don’t want to code, you can download all the source code at GitHub, with the address and link information listed in the following table (github.com/zq2599/blog…
The name of the link note
Project home page Github.com/zq2599/blog… The project’s home page on GitHub
Git repository address (HTTPS) Github.com/zq2599/blog… The project source warehouse address, HTTPS protocol
Git repository address (SSH) [email protected]:zq2599/blog_demos.git The project source warehouse address, SSH protocol
  1. This Git project has multiple folders. The application of this chapter is in the Mybatis folder, as shown in the red box below:

Springboot + Mybatis + Druid + Swagger

The steps required for the entire integration are listed below to avoid omission:

  1. Create springBoot project;
  2. Add mybaits, Druid, swagger dependencies to POM. XML;
  3. Configure mybatis – config. XML;
  4. Configure application. Yml, which contains data source, Mybatis, druid;
  5. Springboot starts the class, specifying MapperScan;
  6. Swagger configuration class;
  7. Druid configuration class;
  8. Database entity class;
  9. Mybatis mapper configuration file;
  10. Mapper class of Mybatis;
  11. Business code;
  • Follow-up development can be carried out according to the above list;

The development of

  1. The database and table structure used in this paper is exactly the same as that in MyBatis Primary Combat: Spring Boot integration.
  2. MyBatis is a new project named Druidonesource. It is a new project named Druidonesource. It is a new project named Druidonesource.

Add version management for druid to the parent project:

            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>1.1.17</version>
            </dependency>
Copy the code
  1. The pom.xml for the new project Druidonesource reads as follows:

      
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.bolingcavalry</groupId>
        <artifactId>mybatis</artifactId>
        <version>1.0 the SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <groupId>com.bolingcavalry</groupId>
    <artifactId>druidonesource</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>druidonesource</name>
    <description>Demo project for Mybatis Druid (one datasource) in Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>
        <! -- swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
Copy the code
  1. New mybatis – config. XML:
<! DOCTYPEconfiguration
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <! Classes in mapping files do not need to write full path
        <package name="com.bolingcavalry.druidonesource.entity"/>
    </typeAliases>
</configuration>
Copy the code
  1. The stat-view-servlet allows you to log in to the druid monitoring page. The stat-view-servlet allows you to log in to the druid monitoring page.
server:
  port: 8080

spring:
  # 1. JDBC data sources
  datasource:
    username: root
    password: 123456
    url: JDBC: mysql: / / 192.168.50.43:3306 / mybatis? useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    #2. Connection pool configuration
    druid:
      Initialize the number of connections in the pool
      initial-size: 5
      min-idle: 5
      max-active: 20
      Set the connection wait timeout
      max-wait: 60000
      Configure how often to detect idle connections that need to be closed, in milliseconds
      time-between-eviction-runs-millis: 60000
      Set the minimum time for a connection to live in the pool in milliseconds
      min-evictable-idle-time-millis: 30000
      Set the maximum number of milliseconds for a connection to live in the pool
      max-evictable-idle-time-millis: 300000
      validation-query: SELECT 1 FROM user
      test-while-idle: true
      test-on-borrow: true
      test-on-return: false
      PreparedStatement (PSCache) preparedStatement (PSCache) preparedStatement (PSCache
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      # Configure the filters for monitoring statistics interception. After removing the filters, the MONITORING interface SQL cannot be counted. 'wall' is used for the firewall
      filters: stat,wall,slf4j
      filter:
        stat:
          merge-sql: true
          slow-sql-millis: 5000
      #3. Basic monitoring configuration
      web-stat-filter:
        enabled: true
        url-pattern: / *
        # set which urls are not counted
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
        session-stat-enable: true
        session-stat-max-count: 100
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        reset-enable: true
        Set the login name and password of the monitoring page
        login-username: admin
        login-password: admin
        allow: 127.0. 01.
        # deny: 192.168.1.100

# mybatis configuration
mybatis:
  # Config file location
  config-location: classpath:mybatis-config.xml
  # Map file location
  mapper-locations: classpath:mappers/*Mapper.xml

# log configuration
logging:
  level:
    root: INFO
    com:
      bolingcavalry:
        druidonesource:
          mapper: debug
Copy the code
  1. To create a startup class, use the MapperScan annotation:
package com.bolingcavalry.druidonesource;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.bolingcavalry.druidonesource.mapper")
public class DuridOneSourceApplication {

    public static void main(String[] args) { SpringApplication.run(DuridOneSourceApplication.class, args); }}Copy the code
  1. Create swagger configuration class
package com.bolingcavalry.druidonesource;

import springfox.documentation.service.Contact;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/ * * *@Description: Swagger configuration class *@author: willzhao E-mail: [email protected]
 * @date: 2020/8/11 when * /
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .tags(new Tag("UserController"."User Services"), new Tag("LogController"."Log Service"))
                .select()
                // The current package path
                .apis(RequestHandlerSelectors.basePackage("com.bolingcavalry.druidonesource.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    // Build the details function of the API document, note which annotation here refers to
    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                // Page title
                .title("MyBatis CURD operation")
                / / founder
                .contact(new Contact("Programmer Chen"."https://github.com/zq2599/blog_demos"."[email protected]"))
                / / version number
                .version("1.0")
                / / description
                .description("API description") .build(); }}Copy the code
  1. Druid datasource = druid datasource = druid datasource = druid datasource
package com.bolingcavalry.druidonesource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/ * * *@Description: druid configuration class *@author: willzhao E-mail: [email protected]
 * @date: 2020/8/18 08:12 * /
@Configuration
public class DruidConfig {

    private static final Logger logger = LoggerFactory.getLogger(DruidConfig.class);

    @Value("${spring.datasource.url}")
    private String dbUrl;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.druid.initial-size}")
    private int initialSize;
    @Value("${spring.datasource.druid.max-active}")
    private int maxActive;
    @Value("${spring.datasource.druid.min-idle}")
    private int minIdle;
    @Value("${spring.datasource.druid.max-wait}")
    private int maxWait;
    @Value("${spring.datasource.druid.pool-prepared-statements}")
    private boolean poolPreparedStatements;
    @Value("${spring.datasource.druid.max-pool-prepared-statement-per-connection-size}")
    private int maxPoolPreparedStatementPerConnectionSize;
    @Value("${spring.datasource.druid.time-between-eviction-runs-millis}")
    private int timeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.druid.min-evictable-idle-time-millis}")
    private int minEvictableIdleTimeMillis;
    @Value("${spring.datasource.druid.max-evictable-idle-time-millis}")
    private int maxEvictableIdleTimeMillis;
    @Value("${spring.datasource.druid.validation-query}")
    private String validationQuery;
    @Value("${spring.datasource.druid.test-while-idle}")
    private boolean testWhileIdle;
    @Value("${spring.datasource.druid.test-on-borrow}")
    private boolean testOnBorrow;
    @Value("${spring.datasource.druid.test-on-return}")
    private boolean testOnReturn;
    @Value("${spring.datasource.druid.filters}")
    private String filters;
    @Value("{spring.datasource.druid.connection-properties}")
    private String connectionProperties;

    /** * Druid connection pool configuration */
    @Bean
    public DruidDataSource dataSource(a) {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setMaxEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setFilters(filters);
        } catch (Exception e) {
            logger.error("druid configuration initialization filter", e);
        }
        datasource.setConnectionProperties(connectionProperties);
        returndatasource; }}Copy the code
  1. The following data entity class, MAPper configuration, Mapper interface class, business code, etc., in addition to the package is not the same, the other and the previous chapter “MyBatis primary actual war ii: add, delete, change and check” exactly the same, please refer to github source code or the previous article to write, here will not take up the space;

Unit testing (special attention)

When unit testing, a special concern is to turn off the monitoring function, otherwise the unit test will fail;

  1. Create a new file named application-test.yml with the same contents as application-.yml except for the values in the red box below:

  1. The unit test class UserControllerTest is the same as that in the previous chapter. The red box is added to specify the use of the application-test.yml configuration file:

Validation, unit testing

The operations in the red box below can complete the unit test:

Validation, swagger

  1. Start the application running DuridOneSourceApplication classes;
  2. Browser: http://localhost:8080/swagger-ui.htm, the operation is as follows:

Select * from primary key where ID = 1;

  1. Other interfaces can also be completed on swagger page by similar operations;

Verify that the Druid connection pool is used

  1. Spring boot datasource = druid datasource = druid datasource = druid datasource = druid datasource = druid datasource = druid datasource = druid datasource View data source instance;
  2. Put a breakpoint on the insertWithFields method of the UserMapper interface, as shown in the red box:

3. The diagram below, click the right mouse button on the DuridOneSourceApplication class, choose the option in the red box, namely to debug ways to start the application:

4. The startup log is displayed in the red box below, indicating that the startup speed is slow in debug mode. Please wait patiently:

Druid = druid; druid = druid; druid = druid; druid = druid;

6. The project curd does not use Druid, so let’s break it to see what the data source looks like.

Experience druid’s monitoring page

  1. Start the application execution DuridOneSourceApplication classes;
  2. Browser visit: http://localhost:8080/druid, the following diagram, account password is admin (in application. The configuration of yml) :

  1. SQL > select * from ‘swagger’; SQL > select * from ‘Swagger’;

  • Springboot + Mybatis + Druid integration development and verification is complete, I hope this article can give you some reference;

You are not alone, Xinchen original accompany all the way

  1. Java series
  2. Spring series
  3. The Docker series
  4. Kubernetes series
  5. Database + middleware series
  6. The conversation series

Welcome to pay attention to the public number: programmer Xin Chen

Wechat search “programmer Xin Chen”, I am Xin Chen, looking forward to enjoying the Java world with you…

Github.com/zq2599/blog…