[deploying springboot project to docker] 2. Building a simple project with springboot + mybatis + Druid

Time:2021-1-20

Write on the front

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

If you talk about the content of the last article, you can go to my last article first
[deploying springboot project to docker] 1. Building an Ubuntu docker environment

Springboot! Simplify, simplify, simplify!

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

Fill in the project properties and add spring web dependencies
[deploying springboot project to docker] 2. Building a simple project with springboot + mybatis + Druid

[deploying springboot project to docker] 2. Building a simple project with springboot + mybatis + Druid

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

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

At this point, there is no need to configure any cumbersome
web.xml
spring-serlet.xml
applicationContext.xml
All you need to do is application.properties The basic content can be configured for use (even if it is not configured, it will be started according to the default configuration)
Like the following~~~

#application.properties
#Specify the listening port for web startup. 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 (the annotated class @ springbootapplication)
This is the package structure recommended by most developers

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


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

About mybatis and Druid

In fact, I really don’t like mybatis. I always think that this way of configuring SQL with XML is too anti-human. But this is the domestic environment. Hey, he even tested you mybatis in the interview, and I dare not to be familiar with it.
So, I learned about it on springboot. If you develop with mybatis quickly, in fact, mybatis also makes a dependency package for integrating springboot

mybatis-spring-boot-starter

Well, the official document recommends using annotations to write SQL for rapid development. The development is fast, and the maintenance will be fast in the future. There are still many problems caused by writing annotations to SQL, so we still need to find an auxiliary tool, mybatis plus. There are many such auxiliary tools, such as tk.mybatis Choice is a choice that I follow the principle of simplicity and quickness.

Druid is a data connection pool developed by Alibaba. To tell you the truth, my knowledge of this area only stays in database connection management, reducing the consumption of establishing database connection, because they are all write and use, and I have to supplement this knowledge in the future. In addition to its performance is no worse than other popular connection pools, Druid also has a monitoring service. I really want to play with it. At the same time, Druid also has an integrated version of springboot, called

druid-spring-boot-starter
Supplementary information: Druid manual

First, add the following dependencies to the 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>

Next, a terrible thing will happen, that is, the configuration file is very long, and it may become longer and longer in the future, so you can try to change it to YML configuration. Springboot supports configuration files in this format by default. I will not change my project for the time being, just remember to have YML

Configure mybatis and Druid

Because they all use the spring boot version dependency, they only need to write according to the official configuration document application.properties Just fine.
Here is a simple configuration:
Open the Druid monitoring and statistics function, monitor the 8082 port, connect to the local database float, and specify the data source

server.port=8082
#Mybatis configuration, temporarily not available
#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, minimum, maximum
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
#Configure the time to wait for a connection to time out
spring.datasource.druid.max-wait=60000
#Configure how often to detect 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
#Turn on 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 filters for monitoring and statistics interception. After removing the monitoring interface, SQL cannot be counted, 'wall' is used for firewall, and log4j2 is used to output SQL logs
spring.datasource.druid.filters=stat,wall
#Open the mergesql function through the connectproperties property; slow SQL record
spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#Merging 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 several 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 mentioned above.)

[deploying springboot project to docker] 2. Building a simple project with 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 from hump to underline by default 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 in application.Java If mapperscan scan is defined in the startup class, it is necessary to write this annotation
//Inheriting the basemapper < entity > of mybatis plus, the basic query does not 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 routine
@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, monitor 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.
[deploying springboot project to docker] 2. Building a simple project with springboot + mybatis + Druid

Druid background monitoring

The background configuration of Druid has been written in the applicaiton configuration. We can access the local address of the project, and then add / Druid after 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

[deploying springboot project to docker] 2. Building a simple project with springboot + mybatis + Druid

You can see the user SQL you just accessed the usercontroller query

last

In general, the steps are still very simple. In fact, I spent a lot of time studying Druid, because the Druid springboot documents are not complete, which has tormented me for several days.
There is also a new logging framework, log4j2. After startup, you can’t miss the Key log output. Springboot uses common logging by default. Well, it doesn’t seem to work very well, but I’ll leave it to the next one.

It’s labor day. Let’s have a rest and study the next stage,
The next article focuses on: log framework log4j2 + springboot background docker deployment
I hope I can write it soon. Happy holidays~

Recommended Today

All domestic images in one station

In the development process, we often use a variety of package management tools. Almost every package management tool is set to download the corresponding software installation package from a foreign server by default, or it is slow to download, or it can’t be downloaded at all. The following is a list of all my commonly […]