1. Introduction

In the previous article Spring Boot (Seven) : In Mybatis minimal Configuration, we introduced the basic usage of Mybatis in Spring Boot. One of the defects is that Mybatis itself does not provide paging function. We also need to manually add the PageHelper plug-in or implement the paging tool class by ourselves, and it is not friendly to the operation of a single table. Simple INSERT, update and DELETE also require us to add SQL statements. Under the current micro-service architecture mode, Each service has its own separate database, single table usage scenarios will be more and more, the use of Mybatis will undoubtedly produce a lot of repeated labor.

Mybatis Plus emerges at the historic moment in this context. Mybatis -Plus (MP for short) is an enhancement tool of Mybatis. Based on Mybatis, it only enhances and does not change, and is born to simplify development and improve efficiency. The open source team’s vision for the open source project is as follows:

vision

Our vision is to become the best partner of MyBatis, just like 1P and 2P in Contra, the efficiency of gay friends is doubled.

2. The characteristics of

  • No intrusion: only enhancements are made, no changes are made, and its introduction will not affect the existing project, as smooth as silk
  • Low loss: Basic CURD will be injected automatically upon startup, with basically no loss in performance and direct object-oriented operation
  • Powerful CRUD operations: built-in universal Mapper, universal Service, only through a small amount of configuration can achieve a single table most CRUD operations, more powerful condition constructor, to meet all types of use requirements
  • Support Lambda form call: through Lambda expressions, it is convenient to write all kinds of query conditions, without worrying about field write errors
  • Support automatic generation of primary keys: support up to four primary key policies (including distributed unique ID generator – Sequence), can be freely configured, perfect solution to the primary key problem
  • Support for ActiveRecord mode: Support for ActiveRecord form calls, entity classes only need to inherit from Model classes to perform powerful CRUD operations
  • Support custom global universal operations: support Write once (use anywhere)
  • Built-in code generator: using code or Maven plug-in can quickly generate Mapper, Model, Service, Controller layer code, support template engine, more than a lot of custom configuration you to use
  • Built-in paging plug-in: Based on MyBatis physical paging, developers do not need to care about specific operations, after configuring the plug-in, write paging is equal to ordinary List query
  • The paging plug-in supports a variety of databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer2005, SQLServer and many other databases
  • Built-in performance analysis plug-in: outputs Sql statements and their execution time. It is recommended to enable this function during development and testing to quickly find out slow queries
  • Built-in global interception plug-in: provides intelligent analysis and blocking of delete and UPDATE operations on all tables, and can customize interception rules to prevent misoperations

Mybatis compared – Plus Mybatis better support the related operation of single table, and directly support paging, also join a series of help develop plug-ins, relevant recommend readers visit the website for details: https://mybatis.plus/guide/. The following will introduce Mybatis-Plus single table operation and the introduction of SQL analysis plug-in.

3. Engineering practice

3.1 The project relies on POM. XML as follows:

Code listing: spring-boot-mybatis-plus/ pum.xml ***

< the dependency > < groupId > com. Baomidou < / groupId > < artifactId > mybatis - plus - the boot - starter < / artifactId > < version > 3.2.0 < / version >  </dependency> <! -- https://mvnrepository.com/artifact/p6spy/p6spy --> <dependency> <groupId>p6spy</groupId> < artifactId > p6spy < / artifactId > < version > 3.8.6 < / version > < / dependency >Copy the code

  • Mybatis -plus-boot-starter is the required dependency of mybatis- Plus
  • P6spy is a print dependency for SQL analysis. If not needed, mybatis-plus-boot-starter can be introduced separately.

3.2 configuration

The configuration file application.yml is as follows:

Code listing: spring – the boot – mybatis – plus/SRC/main/resources/application. The yml * * *

server: port: 8080 spring: application: name: spring-boot-mybatis-xml datasource: url: JDBC: p6spy: mysql: / / 172.16.96.112:3306 / test? serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false username: root password: 123456 driver-class-name: com.p6spy.engine.spy.P6SpyDriver type: com.zaxxer.hikari.HikariDataSource hikari: auto-commit: true minimum-idle: 2 idle-timeout: 60000 connection-timeout: 30000 max-lifetime: 1800000 pool-name: DatebookHikariCP maximum-pool-size: 5 # mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImplCopy the code

Note: Enable SQL analysis printing for Mybatis – Plus

  • Need to configure themybatis-plus.configuration.log-impl
  • Modify the configurationspring.datasource.driver-class-namecom.p6spy.engine.spy.P6SpyDriverThis configuration uses the driver class provided by P6Spy.
  • The URL prefix is JDBC: p6SPY followed by a colon for the corresponding database connection address.
  • This plug-in has performance loss and is not recommended for production environments.
  • Add spy.properties as follows:

Code listing: spring – the boot – mybatis – plus/SRC/main/resources/spy. The properties of * * *

Module. The log = com. P6spy. Engine. Logging. P6LogFactory, com. P6spy. Engine. The outage. P6OutageFactory # custom log print LogMessageFormat = com. Baomidou. Mybatisplus. The extension. P6spy. # P6SpyLogger log output to the console Appender = com. Baomidou. Mybatisplus. The extension. P6spy. StdoutLogger # using logging system record SQL # appender = com. P6spy. Engine. Spy. Appender. Slf4JLogger # set p6spy driver agent deregisterdrivers JDBC URL prefix = true # cancelled Useprefix = true # configuration record Log exceptions, can get rid of the result set of the error, the info of batch, debug, statement, commit, rollback, the result, the resultset. Excludecategories = info, debug, result, batch, the resultset # date format dateformat = yyyy - MM - dd HH: MM: ss # actual drive is multiple Driverlist =org.h2.Driver # Whether to enable outageDetection =true # Slow SQL detection standard 2 seconds outageDetectionInterval =2Copy the code

3.3 the Mapper class

Code listing: spring – the boot – mybatis – plus/SRC/main/Java/com/springboot springbootmybatisplus/mapper/UserMapper. Java * * *

public interface UserMapper extends BaseMapper<User> {
}Copy the code

Here you just need to inherit BaseMapper, BaseMapper provides us with rich single table operation, the operation of the specific com. Can view the source code. Baomidou mybatisplus. Core. Mapper. BaseMapper, the comments are very detailed.

3.4 the Service class

Mybatis-Plus provides the IService interface, a generic Service CRUD package, in addition to the basic Mapper class. CRUD uses get query single row remove delete list query set Page paging prefix naming to distinguish Mapper layer to avoid confusion. If it is possible to customize the general Service method, please create your own IBaseService that inherits the base class provided by Mybatis-Plus.

The userservice.java code looks like this:

Code listing: spring – the boot – mybatis – plus/SRC/main/Java/com/springboot springbootmybatisplus/service/UserService Java * * *

public interface UserService extends IService<User> {
}Copy the code

The userServicePl. Java code looks like this;

Code listing: spring – the boot – mybatis – plus/SRC/main/Java/com/springboot springbootmybatisplus/service/impl UserServiceImpl. Java * * *

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}Copy the code

The relevant test code has been created for the test Controller, which is not listed here. Readers who need it can access the Github repository for their own use.

3.5 Paging configuration classes

Code listing: spring – the boot – mybatis – plus/SRC/main/Java/com/springboot/springbootmybatisplus/config/MybatisPlusConfig Java * * *

@configuration Public class MybatisPlusConfig {@return */ @bean public PaginationInterceptor paginationInterceptor(){ return new PaginationInterceptor(); }}Copy the code

4. Test

After start the project, open the browser to access: http://localhost:8080/findPage, you can see the json returned to normal, as follows:

{ "records":[ { "id":"a0ac692d-e1f1-11e9-9a69-0242ac110002", "nickName":"geekdigging.com", "age":108, "CreateDate", "the 2019-09-28 T13: abominable. 000 + 0000"}, {" id ":" b9168576 - e1f1 e9-9-11 ac110002 a69-0242 ", NickName :"www.geekdigging.com", "age":18, "createDate":" 2019-09-28t13:12.000 +0000"}], "total":2, "size":5, "current":1, "orders":[ ], "searchCount":true, "pages":1 }Copy the code

SQL analysis logs are displayed as follows:

Logs help you clearly see the current log execution process, what is executed first and then what is executed, and how much time is spent. This helps you analyze SQL performance and know which SQL takes a long time.

5. Summary

The overall use of Mybatis-Plus is relatively simple, the use of Mybatis-Plus are supported, Mybatis.*** should be replaced with Mybatis -plus.***, and it enhances the limitations of mybatis’ single-table operation. Make only enhancement do not change, to simplify development, improve efficiency. I think it is very appropriate. This article only introduces some basic use of Mybatis-Plus, in addition to the official enhanced single table operation, paging, SQL analysis and other functions, but also provides a lot of practical plug-ins, such as: Hot loading, logical deletion, SQL injector, attack SQL block parser and other functions, if there is a need for readers can access the official documents themselves.

5. Sample code

Example code -Github

Example code -Gitee

6. Reference

Mybatis-Plus Official Document