Reference: Mybatis – Plus website address: mp.baomidou.com BiliBili: crazy god said Java – MyBatisPlus latest complete tutorial easy to understand

First, brief introduction

Mybatis-Plus is an enhancement tool of Mybatis, on the basis of Mybatis only do enhancement do not change.

Designed to simplify development and improve efficiency, all CRUD can be automated.

Reference mode:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatis.plus.version}</version>
</dependency>
Copy the code

Second, actual combat training

1. Create a database

- to build library
CREATE DATABASE IF NOT EXISTS `mybatis_plus` -- database name
CHARACTER SET 'utf8'                         -- Set character set
COLLATE 'utf8_general_ci';                   Set collation rules

- a table
DROP TABLE IF EXISTS user;

CREATE TABLE user
(
	id BIGINT(20) NOT NULL COMMENT 'primary key ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT 'name',
	age INT(11) NULL DEFAULT NULL COMMENT 'age',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT 'email'.PRIMARY KEY (id)
);

-- Add data
DELETE FROM user;

INSERT INTO user (id, name, age, email) VALUES
(1.'Jone'.18.'[email protected]'),
(2.'Jack'.20.'[email protected]'),
(3.'Tom'.28.'[email protected]'),
(4.'Sandy'.21.'[email protected]'),
(5.'Billie'.24.'[email protected]');
Copy the code

2. Create a Springboot project

Delete redundant files, the project directory is as follows:

The configuration file POM. XML contains the following contents:


      
<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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/> <! -- lookup parent from repository -->
    </parent>

    <groupId>cc.xiaoming</groupId>
    <artifactId>mybatis_plus</artifactId>
    <version>1.0.0</version>
    <name>mybatis_plus</name>
    <description>Practice MybatisPlus</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
Copy the code

3. Import dependencies

With myBatis plus, there is no need to import MyBatis.

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.2</version>
</dependency>
Copy the code

4. Connect to the database

In application. Yml, the content is the same as that of mybatis:

# Database configuration
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis_plus? characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asi a/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
Copy the code

“Entity-controller-service-mapper-xml” is the next step in mybatis, and each SQL statement has to be written by itself (I don’t know mybatis very well at present, so stop there).

But let’s just write it as myBatis plus does.

5. Write a class

Entity class

package cc.xiaoming.entity;

import lombok.Data;

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
Copy the code

mapper

package cc.xiaoming.mapper;

import cc.xiaoming.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface UserMapper extends BaseMapper<User> {
    // Nothing
    // UserMapper inherits BaseMapper (already implements all CRUD operations)
    // You don't need to manually write SQL statements as before; But you can also write your own extension methods
}
Copy the code

Start the class

package cc.xiaoming;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("cc.xiaoming.mapper")
@SpringBootApplication
public class MybatisPlusApplication {

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

6. BaseMapper

Here are the CRUD operations it has implemented.

package com.baomidou.mybatisplus.core.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;

public interface BaseMapper<T> extends Mapper<T> {
    int insert(T entity);

    int deleteById(Serializable id);

    int deleteByMap(@Param("cm") Map<String, Object> columnMap);

    int delete(@Param("ew") Wrapper<T> queryWrapper);

    int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);

    int updateById(@Param("et") T entity);

    int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);

    T selectById(Serializable id);

    List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);

    List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);

    T selectOne(@Param("ew") Wrapper<T> queryWrapper);

    Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);

    List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);

    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);

    List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);

    <E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);

    <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);
}
Copy the code

7. Test use

Test. The Java. Cc. Xiaoming. MybatisPlusApplicationTests test class:

package cc.xiaoming;

import cc.xiaoming.entity.User;
import cc.xiaoming.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.List;

@SpringBootTest
class MybatisPlusApplicationTests {

    @Resource
    private UserMapper userMapper;

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

The selectList() method in UserMapper takes parameters inside the conditional Wrapper built into Mybatis-Plus, which means to query according to the conditions. Therefore, if you do not fill in the parameters, there will be no conditions, i.e. all data will be queried.

Here are the results:

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)
Copy the code

8. Print the SQL statement

In the above code, we did not write the SQL statement, but the query results, it is not difficult to guess that Mybatis-Plus has written for us.

Currently all of our SQL is invisible, and we want to know how it is executed, which can be seen in the log.

Configuration file application.yml with:

# Mybatis configuration
mybatis-plus:
  configuration:
    # Print out the executed SQL statements, which can be used in development and testing
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Copy the code

Execute the test class to view the console logs:

JDBC Connection [HikariProxyConnection@ 225507106 wrapping com.mysql.cj.jdbc.ConnectionImpl@1e1eeedd] 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@38830ea]
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)
Copy the code

9. To be continued…