SpringBoot integrates MyBatis-Plus introductory experience

Keywords: Programming Mybatis MySQL xml Database

I. Preface

This article will integrate MyBatis-Plus based on SpringBoot. MyBatis-Plus is an enhancement tool for MyBatis, which enhances MyBatis without changing its original function.~

2. SpringBoot Integration MyBatis-Plus

Basic environment
  1. spring-boot 2.1.8
  2. mybatis-plus 2.2.0
  3. mysql 5.7.24
  4. maven project

1. Introducing MyBatis-Plus dependencies into pom.xml

Next, paste the whole document content of the small edition directly for reference, so as to avoid errors caused by missing some details.

<?xml version="1.0" encoding="UTF-8"?>
<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">
        <relativePath/> <!-- lookup parent from repository -->
    <description>Demo project for Spring Boot</description>



        <!-- mybatis-plus begin =================================== -->
        <!-- mybatis-plus end -->

        <!-- ========================= Database correlation ========================== -->
        <!-- Ali database connection pool -->

        <!-- ========================= Common library dependencies ========================== -->
        <!-- lombok Plug-in unit -->
        <!-- Hutool Tool class -->
        <!-- StringUtils Tool class -->

        <!-- Note: maven The default is not compiled, so add the following resources Only then will the corresponding production be produced. xml Document Purpose: Resolution mybatis Mapping relationship miscorrespondence  start =============== -->
        <!-- Note: maven The default is not compiled, so add the following resources Only then will the corresponding production be produced. xml Document Purpose: Resolution mybatis Mapping relationship miscorrespondence  end =============== -->


2. MyBatis-Plus configuration class

Here we mainly configure paging plug-ins and @MapperScan annotations to scan Mapper folders

@MapperScan("com.zhengqing.demo.modules.**.mapper*") // Scanning the Mapper folder
public class MybatisPlusConfig {
     * mybatis-plus Paging plug-in <br>
     * Document: https://mp.baomidou.com/guide/page.html <br>
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();

3. Configuration of database and mybatis-plus configuration in application.yml

Warm Tip: Pay attention to modifying your database connection configuration information~

# configure port
  port: 8080
    #    context-path: /api
    application-display-name: demo

        name: demo
      active: dev
    # Configuring data sources
      url: jdbc:mysql:// Allow MultiQueries = true & useUnicode = true & characterEncoding = UTF8 & zeroDateTime Behavior = convertToNull & useSSL = false # MySQL in high versions need to specify whether or not to make an SSL connection solution plus & useSSL = false
      name: demo
      username: root
      password: root
      # Using druid data source
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      filters: stat
      maxActive: 20
      initialSize: 1
      maxWait: 60000
      minIdle: 1
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: select 'x'
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      maxOpenPreparedStatements: 20

    enabled: false

# Configuration of mybatis plus
  # XML scanning, where multiple directories are separated by commas or semicolons (telling Mapper the location of the corresponding XML file)
  mapper-locations: classpath:**/*Mapper.xml
  # The following configurations have default values and can be set without setting
    #Primary key type 0: "database ID self-increasing", "user input ID", "global unique ID", "global unique ID", "global unique ID", "global unique ID UUID";
    id-type: 0
    #Field Strategy 0: "Ignore Judgment", "Non-NULL Judgment", "Non-empty Judgment"
    field-strategy: 2
    #Conversion of Hump Underline
    db-column-underline: true
    #Refresh mapper debugging artifact
    refresh-mapper: false
    #Database Uppercase Underline Conversion
    #capital-mode: true
    #Sequence Interface Implementing Class Configuration
    #key-generator: com.baomidou.springboot.xxx
    #Logical Delete Configuration
    #logic-delete-value: 0 # Logically deleted values (default 1)
    #logic-not-delete-value: 1 # Logical Undeleted Value (default 0)
    #Implementation of Custom Filling Policy Interface
#    meta-object-handler: com.zhengqing.config.MyMetaObjectHandler
    #Custom SQL Injector
    #sql-injector: com.baomidou.springboot.xxx
    # Whether to turn on Automatic Hump naming rule mapping: a similar mapping from database column names to Java attribute hump naming
    map-underscore-to-camel-case: true
    cache-enabled: false
    # If the query results contain columns with null values, MyBatis does not map this field when mapping
#    call-setters-on-nulls: true
    # This configuration prints out the sql executed and can be used during development or testing
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    # Resolve the problem that oracle cannot convert errors when updating data to null, and mysql will not.
    jdbc-type-for-null: 'null'

III. simulation business code - CRUD user information table

1. New t_sys_user user table in database

2. Writing Entity Classes

Warm Tip: Entity class inherits MyBatis-Plus Model class + Mapper class inherits MyBatis-Plus BaseMapper class - > can support ActiveRecord dynamic grammar calls

public class User extends Model<User> {

    private static final long serialVersionUID = 1L;

     * Primary key ID
	@TableId(value="id", type= IdType.AUTO)
	private Integer id;
     * Account number
	private String username;
     * Login password
	private String password;
     * Nickname?
	private String nickName;

	protected Serializable pkVal() {
		return this.id;

3. Writing Mapper classes

public interface UserMapper extends BaseMapper<User> { }

IV. Testing CRUD

Warm Tip: The following CRUD s all use ActiveRecord dynamic grammar

public class ApplicationTests {
     * New data
    public void testAdd() throws Exception{
        User entity = new User();

     * Update data
    public void testUpdate() throws Exception{
        User entity = new User();
        entity.setNickName("Test number");

     * Delete data
    public void testDelete() throws Exception{
        User entity = new User();

     * Query specified id data
    public void testSelectById() throws Exception{
        User entity = new User();
        User user = entity.selectById(1);

     * Query all data
    public void testSelectAll() throws Exception{
        User entity = new User();
        List list = entity.selectList(null);

     * Query all data - paging
    public void testSelectAllPage() throws Exception{
        User entity = new User();
        Page<User> page = entity.selectPage(new Page<User>(1, 10), null);

V. Native MyBatis Approach

Let's put the demo source code at the end of this case, not to mention more, that is to say, write sql statements to deal with the corresponding business.

Six, summary

  1. Introducing Relevant Dependencies
  2. MyBatis-Plus Core Configuration - Packet Sweeping, Aliases, Paging Plug-ins, etc.
  3. Write business code tests

Overall, it's relatively simple. For more grammar and functions about MyBatis-Plus, refer to the MyBatis-Plus official documentation.


Overall project structure:

The source code of this case


The actual operation of the project can be referred to:
GitHub address: https://github.com/zhengqingya/code-generator
Code Cloud Address: https://gitee.com/zhengqingya/code-generator

This article by the blog article multiple platform OpenWrite Release!

Posted by Oren on Thu, 10 Oct 2019 19:58:11 -0700