Mybatis plus study notes

Keywords: Java Mybatis MybatisPlus

Chapter 1 MybatisPlus quick start

1. MybatisPlus overview

MybatisPlus: an enhanced toolkit for Mybatis

MybatisPlus official website: https://mybatis.plus/ or https://mp.baomidou.com/

MyBatis plus (MP for short) is an enhancement tool of MyBatis. On the basis of MyBatis, it is only enhanced without change. It is born to simplify development and improve efficiency.

Vision: our vision is to become the best partner of MyBatis, just like 1P and 2P in soul duel. With the combination of friends and friends, the efficiency will be doubled.

Features of MybatisPlus

  • No invasion: it is only enhanced without change, and its introduction will not affect the existing project, which is as smooth as silk
  • Low loss: the basic fuel will be injected automatically upon startup
  • CURD, basically no performance loss, direct object-oriented operation
  • Powerful crud operation: built in general Mapper and general Service, most CRUD operations of a single table can be realized only through a small number of configurations, and there is a powerful condition constructor to meet various use requirements
  • Support Lambda formal call: it is convenient to write various query conditions through Lambda expression, and there is no need to worry about wrong fields
  • Support automatic generation of primary key: support up to 4 primary key strategies (including distributed unique ID generator - Sequence), which can be configured freely to perfectly solve the primary key problem
  • Support ActiveRecord mode: support ActiveRecord formal calls. Entity classes only need to inherit Model classes to perform powerful CRUD operations
  • Support custom global general operations: support global general method injection (Write once, use anywhere)
  • Built in code generator: code or Maven plug-in can be used to quickly generate Mapper, Model, Service and Controller layer code, support template engine, and more custom configurations for 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, writing paging is equivalent to ordinary List query
  • The paging plug-in supports multiple databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases
  • Built in performance analysis plug-in: it can output 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: it provides intelligent analysis and blocking of full table delete and update operations, and can also customize interception rules to prevent misoperation

MybatisPlus document address

Official address: http://mp.baomidou.com perhaps https://mybatis.plus/
Code release address:
Github: https://github.com/baomidou/mybatis-plus
Gitee: https://gitee.com/baomidou/mybatis-plus
Document publishing address: https://mp.baomidou.com/guide/

2. MybatisPlus quick start

2.1 environment construction

Refer to mybatis plus Official website

1. Create database tables

idnameageemail
1Jone18test1@baomidou.com
2Jack20test2@baomidou.com
3Tom28test3@baomidou.com
4Sandy21test4@baomidou.com
5Billie24test5@baomidou.com

The corresponding database Schema script is as follows:

-- Create database
CREATE DATABASE mybatis_plus;
--Create user table
CREATE TABLE user
(
	id BIGINT(20) NOT NULL COMMENT 'Primary key ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT 'full name',
	age INT(11) NULL DEFAULT NULL COMMENT 'Age',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT 'mailbox',
	PRIMARY KEY (id)
);

The corresponding database Data script is as follows:

--insert data
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');

2. Add dependency

Import Spring Boot Starter parent project:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>spring-latest-version</version>
    <relativePath/>
</parent>

Spring boot starter, spring boot starter test, mybatis plus boot starter and mysql dependencies are introduced:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.2</version>
    </dependency>
</dependencies>

3. Create entity classes and Mapper mapping interfaces

Create User entity class: it is better to use wrapper type instead of basic type for the fields of entity class. Because each basic type has a default value, it is difficult to distinguish between the value of the database record and the default value of the field when querying. However, the wrapper type does not. If no value is set for the wrapper type, its value is null

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private Long id;
    private String name;
    private Integer age;
    private String email;

}

Create a UserMapper mapping interface that inherits the BaseMapper interface of mybatis plus

@Repository
public interface UserMapper extends BaseMapper<User> {

}

4. Create main startup class

Add the @ MapperScan annotation in the Spring Boot startup class to scan the package where the Mapper interface is located

@SpringBootApplication
@MapperScan("com.potato.mapper")
public class MybatisPlusApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusApplication.class, args);
    }

}

5. Write configuration file

Configure the data source information in the application.yml configuration file. Note: the low version MySQL driver is com.mysql.jdbc.Driver, and there is no need to configure the time zone; The MySQL driver of the higher version is com.mysql.cj.jdbc.Driver, and the time zone configuration needs to be added

# Data source configuration
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis_plus? useUnicode=true&amp;characterEncoding=utf8&amp;autoReconnect=true&amp;allowMultiQuerie s=true&amp;useSSL=false
    username: root
    password: root

6. Code test

@RunWith(SpringRunner.class): This is the annotation provided by junit, which allows the test to run in the Spring test environment and allows the SpringRunner class to provide the Spring test context
@SpringBootTest: the annotation of the SpringBoot test class, which will start the SpringBoot application and create the ApplicationContext object in the test
The parameter of the selectList() method in UserMapper is the MP built-in conditional Wrapper, so it is unconditional if it is not filled in

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisPlusTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        List<User> userList = userMapper.selectList(null);
        userList.forEach(System.out::println);
    }

}

2.2. SQL log

View SQL log

In order to be able to observe what MybatisPlus does for us when calling each method? What kind of SQL statement was executed? We need to open the SQL log

# SQL log configuration
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

After opening the log, run the test code again to see the SQL statement executed when calling the Mapper method

DBC Connection [HikariProxyConnection@81505591 wrapping com.mysql.cj.jdbc.ConnectionImpl@7b4acdc2] will not be managed by Spring
==>  Preparing: SELECT id,name,age,email FROM user
==> Parameters: 
<==    Columns: id, name, age, email
<==        Row: 1, Jone, 18, test1@baomidou.com
<==        Row: 2, Jack, 20, test2@baomidou.com
<==        Row: 3, Tom, 28, test3@baomidou.com
<==        Row: 4, Sandy, 21, test4@baomidou.com
<==        Row: 5, Billie, 24, test5@baomidou.com
<==      Total: 5
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@52a70627]
User(id=1, name=Jone, age=18, email=test1@baomidou.com)
User(id=2, name=Jack, age=20, email=test2@baomidou.com)
User(id=3, name=Tom, age=28, email=test3@baomidou.com)
User(id=4, name=Sandy, age=21, email=test4@baomidou.com)
User(id=5, name=Billie, age=24, email=test5@baomidou.com)

2.3 BaseMapper interface

The UserMapper class written by ourselves inherits from the BaseMapper interface, which provides basic addition, deletion, modification and query methods. Therefore, the Mapper interface written by ourselves only needs to inherit the BaseMapper parent interface to obtain the basic addition, deletion, modification and query functions

/**
 * Mapper After inheriting this interface, you can obtain CRUD function without writing mapper.xml file
 * This Mapper supports id generics
 */
public interface BaseMapper<T> extends Mapper<T> {

    /**
     * Insert a record
     *
     * @param entity Entity object
     */
    int insert(T entity);

    /**
     * Delete by ID
     *
     * @param id Primary key ID
     */
    int deleteById(Serializable id);

    /**
     * Delete the record according to the columnMap condition
     *
     * @param columnMap Table field map object
     */
    int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

    /**
     * Delete the record according to the entity condition
     *
     * @param queryWrapper The entity object encapsulates the operation class (can be null, and the entity in it is used to generate the where statement)
     */
    int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * Delete (batch delete according to ID)
     *
     * @param idList List of primary key ID S (cannot be null and empty)
     */
    int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

    /**
     * Modify according to ID
     *
     * @param entity Entity object
     */
    int updateById(@Param(Constants.ENTITY) T entity);

    /**
     * Update the record according to the whereEntity condition
     *
     * @param entity        Entity object (set condition value, nullable)
     * @param updateWrapper The entity object encapsulates the operation class (can be null, and the entity in it is used to generate the where statement)
     */
    int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);

    /**
     * Query by ID
     *
     * @param id Primary key ID
     */
    T selectById(Serializable id);

    /**
     * Query (batch query by ID)
     *
     * @param idList List of primary key ID S (cannot be null and empty)
     */
    List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

    /**
     * Query (based on columnMap criteria)
     *
     * @param columnMap Table field map object
     */
    List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

    /**
     * Query a record according to the entity condition
     *
     * @param queryWrapper Entity object encapsulates operation class (null able)
     */
    T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * Query the total number of records according to Wrapper conditions
     *
     * @param queryWrapper Entity object encapsulates operation class (null able)
     */
    Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * Query all records according to the entity condition
     *
     * @param queryWrapper Entity object encapsulates operation class (null able)
     */
    List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * Query all records according to Wrapper conditions
     *
     * @param queryWrapper Entity object encapsulates operation class (null able)
     */
    List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * Query all records according to Wrapper conditions
     * <p>Note: only the value of the first field is returned</p>
     *
     * @param queryWrapper Entity object encapsulates operation class (null able)
     */
    List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * Query all records (and turn the page) according to the entity condition
     *
     * @param page         Paging query criteria (can be rowboundaries. Default)
     * @param queryWrapper Entity object encapsulates operation class (null able)
     */
    <E extends IPage<T>> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * Query all records (and turn pages) according to Wrapper conditions
     *
     * @param page         Paging query criteria
     * @param queryWrapper Entity object encapsulation operation class
     */
    <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}

Posted by QuizToon on Sat, 18 Sep 2021 05:12:50 -0700