[deployment of springboot project to docker] 2. Simple project of springboot + mybatis + Druid

Time:2020-5-21

Write in front

This article talks about building a simple project with springboot + mybatis + Druid.

If you talk about the content of the previous article, you can read my previous article first
[deploy the springboot project to docker] 1. Build the Ubuntu docker environment

Springboot! Simplify simplify and simplify again!

Springboot is designed to simplify development configuration and improve rapid development efficiency,So I try to follow this principle to build projects.
Springboot also provides developers with a project initialization tool website. When a new project is created in idea, the springboot initializer function is also integrated by default. The process is similar
[deployment of springboot project to docker] 2. Simple project of springboot + mybatis + Druid

Fill in the project properties and add the spring web dependency
[deployment of springboot project to docker] 2. Simple project of springboot + mybatis + Druid

[deployment of springboot project to docker] 2. Simple project of springboot + mybatis + Druid

The simplest springboot web project was quickly created.
Open the POM file and you can see that the spring boot starter web dependency has been added, including spring, spring MVC, Tomcat integration and so on.

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
</dependency>

At this time, you don’t need to configure anything tedious
web.xml
spring-serlet.xml
applicationContext.xml
You just need to application.properties The basic content can be used after configuration (even if it is not configured, it will be started according to the default configuration)
Like the following~~~

#application.properties
#Specify the web start listening port, the default is 8080
server.port=8082
#Data source configuration
#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#spring.datasource.url=jdbc:mysql://localhost:3306/xxx
#spring.datasource.username=root
#spring.datasource.password=password
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
In addition, springboot scans the startup class by default (class @ springbootapplication with this annotation)
This is the package structure recommended by most developers

com
    +- example
    +- myproject
    + - Application.java  (start class)
    |
    +- domain
    |  +- Customer.java
    |  +- CustomerRepository.java
    |
    +- service
    |  +- CustomerService.java
    |
    +- web
    |  +- CustomerController.java
    |


Of course, you can not follow the default scanning mode of springboot, but you have to manually add the component scanning annotation @ componentscan to the startup class

About mybatis, Druid

In fact, I really don’t like mybatis. I always think this way of configuring SQL with XML is too anti-human. But this is the domestic environment. Well, the interview is the only way to test your mybatis. I dare not to be familiar with it.
So, I learned from springboot that if you use mybatis to develop quickly, in fact, mybatis also makes a dependency package for integrating springboot called

mybatis-spring-boot-starter

Well, the official documents recommend using annotation to write SQL for rapid development. The development is fast, and the maintenance can be fast in the future. There are still many problems caused by annotation writing to SQL, so we still need to find a helper tool, namely, mybatis plus. There are many other helper tools, such as tk.mybatis , choice is a choice that I follow the principle of simple and fast.

Druid is a data connection pool developed by Alibaba. To tell you the truth, my knowledge of this pool only stays in database connection management and reduces the consumption of establishing database connection, because they are all write as you go, so I need to supplement this knowledge later. Besides the performance of Druid is no worse than that of other popular connection pools, it also has monitoring service, which makes you want to play hahaha. In the same way, Druid also has a spring boot integrated version, called

druid-spring-boot-starter
Supplement: Druid manual

First, add the following dependencies to POM

    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency> 
    <!-- druid -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.21</version>
    </dependency>
    <!--mybatis-plus-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.3.1.tmp</version>
    </dependency>

The next thing that will happen is that the configuration file is very long, and it may be longer and longer in the future, so you can try to change it to YML configuration. By default, springboot supports this format of configuration file. My project will not change it for the moment, just remember to have YML

Configure mybatis and Druid

Because of the dependency of springboot version, you only need to write it according to the official configuration document application.properties Just fine.
Here is a simple configuration:
Open the Druid monitoring and statistics function, listen to port 8082, connect to the local database float, and specify the data source

server.port=8082
#Mybatis configuration, temporarily unavailable
#mybatis.config-location=classpath:mybatis-config.xml
#Set data source
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/float
spring.datasource.username=root
spring.datasource.password=pw
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#Druid connection pool supplement
#Initialization size, min, Max
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
#Configure the timeout time for getting connection waiting
spring.datasource.druid.max-wait=60000
#Configure how often to check the interval. Check the idle connections that need to be closed, in milliseconds
spring.datasource.druid.time-between-eviction-runs-millis=60000
#Configure the minimum lifetime of a connection in the pool, in milliseconds
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
#Open pscache and specify the size of pscache on each connection
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
#Configure the filters intercepted by monitoring statistics. After removal, the monitoring interface SQL cannot be counted. 'wall' is used for firewall, and log4j2 is used for outputting SQL logs
spring.datasource.druid.filters=stat,wall
#Open mergesql function through connectproperties property; slow SQL record
spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#Merge monitoring data from multiple druiddatasources
#spring.datasource.useGlobalDataSourceStat=true

#Webstatfilter configuration
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*
spring.datasource.druid.web-stat-filter.session-stat-enable=false
spring.datasource.druid.web-stat-filter.session-stat-max-count=1000
spring.datasource.druid.web-stat-filter.principal-session-name=xxx.user
spring.datasource.druid.web-stat-filter.principal-cookie-name=xxx.user
spring.datasource.druid.web-stat-filter.profile-enable=true

#Statviewservlet configuration
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.reset-enable=false
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=123
spring.datasource.druid.stat-view-servlet.allow=127.0.0.1
spring.datasource.druid.stat-view-servlet.deny=192.168.16.111

Then we write some basic files and create a database table user (ID, name, age)

--Table design
CREATE TABLE `user` (
  `ID ` varchar (32) not null comment 'user ID',
  `Name ` varchar (255) not null comment 'nickname',
  `Age ` int (11) default null comment 'age',
  PRIMARY KEY (`ID`) USING BTREE
)Engine = InnoDB default charset = utf8 comment = 'user table';

--Create a piece of data
Insert into ` user '(` ID', 'name', 'age') values ('1 ',' Zhang San ', 18);

Write a few simple business documents, first look at the project structure after writing
(don’t forget the problem of project structure just mentioned above):

[deployment of springboot project to docker] 2. Simple project of springboot + mybatis + Druid

User entity

package com.roy.demo.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;

//Don't forget the annotation, otherwise it will be converted by default from hump to underline according to the entity name
@TableName("user")
public class UserEntity implements Serializable {
    //Don't forget the notes
    @TableId("id")
    private String Id;

    private String name;

    private Integer age;

    public String getId() {
        return Id;
    }

    public void setId(String id) {
        Id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

Usermapper interface

package com.roy.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.roy.demo.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;

//If not application.Java To define mapperscan scan scan in the startup class, write this annotation
//Inheriting the basemapper < entity > of mybatis plus, basic queries don't need to be rewritten any more!
@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {
}

Simple usercontroller

package com.roy.demo.controller;

import com.roy.demo.entity.UserEntity;
import com.roy.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

//There's nothing to say. It's a regular controller
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping("getById")
    public UserEntity getUserById(@RequestParam String id) {
        UserEntity user = userMapper.selectById(id);
        return user == null ? null : user;
    }
}

Springboot starts!

Everything is ready to start. Listen to port 8082. We can access it on the browser
http://127.0.0.1:8082/user/getById?id=1
You can get our user information.
[deployment of springboot project to docker] 2. Simple project of springboot + mybatis + Druid

Druid background monitoring

Druid’s background configuration has written our local address for accessing the project in the applicaiton configuration, and then / Druid can be added to access it
http://127.0.0.1:8082/druid/
Enter the account password in the configuration file, and then you can see the statistics and SQL records

[deployment of springboot project to docker] 2. Simple project of springboot + mybatis + Druid

You can see the user SQL just accessed the usercontroller query

last

Generally speaking, the steps are very simple. In fact, I spent a lot of time studying Druid, because the documents of Druid spring boot are not very complete, which has also tortured me for several days.
There is also a new log framework, log4j2. After startup, the Key log output cannot be reduced. By default, spring boot uses common log. Well, it seems that it is really not easy to use, but this article will not talk about the log first, let’s leave the next one.

It’s labor day. Take a rest and study the next stage,
The next article focuses on: log framework log4j2 + spring boot background docker deployment
I hope I have time to write earlier. Happy holidays~

Recommended Today

Look! The work of civil servants can be done in this way

Look forward to the sixth World Internet Conference in Wuzhen as scheduled. At today’s conference, Xiao Yun brought the “artifact” to help civil servants improve their work efficiency, and the “treasure” at the bottom of the box from brother Pingtou… Let’s have a deeper understanding. Here comes the government nail! Farewell to the traditional working […]