SpringBoot integrated Mybatis-Plus quick start (detailed)

As the official website said, MyBatis-Plus (opens new window) (MP for short) is an enhancement tool for MyBatis (opens new window). On the basis of MyBatis, only enhancements are made without changes, in order to simplify development and improve efficiency. born.
Framework
insert image description here

1. Quick start

Through a simple Demo to illustrate the powerful functions of MyBatis-Plus, before that, we assume that

  • Possess a Java development environment and a corresponding IDE
  • Familiar with Spring Boot
  • Familiar with Maven

1.1 Database preparation

There is an existing User table: the structure is as follows
insert image description here
Database Schema script:

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
    id BIGINT(20) NOT NULL COMMENT '主键ID',
    name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
    age INT(11) NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
);

Database Data script:

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]');

1.2 Initialization project

Tip:
You can use Spring Initializer (opens new window) to quickly initialize a Spring Boot project

1.3 Add Maven dependencies

Introduce Spring Boot Starter parent project:

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

Introduce various dependencies required by SpringBoot to integrate Mybatis-Plus:

         <dependencies>
        <!--mybatis-plus的springboot支持-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.1</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.32</version>
        </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>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>


    </dependencies>

These are the core dependencies. This project also uses the mysql driver and lombok. To integrate mybatis-plus, remove mybatis and mybatis-spring to avoid conflicts. Lombok dependency is to simplify the writing of getter and setter methods of entity classes.

1.4 configuration

Add the relevant configuration of the jdbc database in the application.yml configuration file:

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启sql日志
    map-underscore-to-camel-case: true
    # 该配置就是将带有下划线的表字段映射为驼峰格式的实体类属性
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
    username: root
    password: 20020702

Add in the Spring Boot startup class@MapperScanNote, scan the Mapper folder:

@SpringBootApplication
@MapperScan("com.guo.demo.mapper")//自己的包名
public class Application {
    
    

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

1.5 encoding

Entity class

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    
    
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

Write the UserMapper interface under the Mapper package

@Mapper
public interface UserMapper extends BaseMapper<User> {
    
    
}

1.6 Start using

Add a test class for functional testing:

@SpringBootTest
public class UserServiceImplTest {
    
    

    @Autowired
    UserServiceImpl userService;

    @Test
    public void queryAll() {
    
    
        userService.selectAll().forEach(System.out::println);
    }
}

Prompt that
the parameter of the selectList() method in UserMapper is the built-in conditional wrapper Wrapper of MP, so if you don’t fill it in, there is no condition

Console output:

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. Installation

The new MyBatis-Plus 3.0 version is based on JDK8 and provides lambda calls, so the requirements for installing and integrating MP3.0 are as follows:

  • JDK 8+
  • Maven or Gradle
    Spring Boot
    Maven:
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>最新版本</version>
</dependency>

Spring
Maven:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>最新版本</version>
</dependency>

3. Configuration

The configuration of MyBatis-Plus is extremely simple, we only need some simple configurations to use the powerful functions of MyBatis-Plus!
Spring Boot project

Configure MapperScan annotations

@SpringBootApplication
@MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper")
public class Application {
    
    

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

Spring project

Configure MapperScan

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.baomidou.mybatisplus.samples.quickstart.mapper"/>
</bean>

Adjust SqlSessionFactory to MyBatis-Plus SqlSessionFactory

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
</bean>

Generally speaking, for general simple projects, MyBatis-Plus can be used normally through the above configuration. For details, please refer to the following projects: Spring Boot Quick Start Example(opens new window), Spring MVC Quick Start Example(opens new window).

4. Notes

It is always beneficial to read more official websites.
Refer to the official website for details: https://baomidou.com/pages/223848/

5. Quick test

Automatically import the relevant configuration required for MyBatis-Plus testing, and quickly configure the testing class through the @MybatisPlusTest annotation.
Example project
Official source code: https://github.com/baomidou/mybatis-plus/tree/master/mybatis-plus-boot-starter-test
Add test dependency
Maven:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter-test</artifactId>
    <version>3.5.3.1</version>
</dependency>

Write test cases
Through @MybatisPlusTest, you can quickly write the test class corresponding to Mapper to achieve fast test code

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import static org.assertj.core.api.Assertions.assertThat;

@MybatisPlusTest
class MybatisPlusSampleTest {
    
    

    @Autowired
    private SampleMapper sampleMapper;

    @Test
    void testInsert() {
    
    
        Sample sample = new Sample();
        sampleMapper.insert(sample);
        assertThat(sample.getId()).isNotNull();
    }
}

Guess you like

Origin blog.csdn.net/lj20020302/article/details/129361783