Introduction to MyBatisPlus

Table of contents

1. Introduction to MyBatisPlus

Moisturize things silently

Efficiency first

Rich functions

2. Spring integrates MyBatisPlus

3. SpringBoot integrates MyBatisPlus


1. Introduction to MyBatisPlus

MyBatis-Plus (MP for short) is an enhancement tool for MyBatis. Based on MyBatis, it only enhances without making changes. It is created to simplify development and improve efficiency. The vision of MyBatisPlus is to become the best partner of MyBatis.

Government address:https://baomidou.com/

The following is an introduction to the three major points on the official website.

Moisturize things silently

It only enhances but does not make changes. Its introduction will not affect the existing project and is as smooth as silk.

Efficiency first

With simple configuration, you can quickly perform single-table CRUD operations, saving a lot of time.

Rich functions

Code generation, automatic paging, logical deletion, automatic filling and other functions are all available.

and some others

corn bean ecosystem

2. Spring integrates MyBatisPlus

MyBatisPlus is officially recommended for use in SpringBoot projects. Spring projects can also use MyBatisPlus. First, we use MyBatisPlus in Spring.
1. Prepare data in Mysql:

DROP DATABASE IF EXISTS `school`;

CREATE DATABASE `school`;

USE `school`;
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) DEFAULT NULL,
 `email` varchar(255) DEFAULT NULL,
`gender` varchar(255) DEFAULT NULL,
 `age` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Create a Maven project and introduce dependencies

<dependencies>
        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.4.2</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>
        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>
        <!-- spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.3.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.9</version>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
    </dependencies>

Create entity class

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private Integer id;
    private String name;
    private String email;
    private String gender;
    private Integer age;
}

Create Mapper interface.
When using MyBatis, after writing the Mapper interface, you need to manually write the CRUD method, and you need to manually write the SQL statement corresponding to each method in the Mapper mapping file. In MyBatisPlus, you only need to create a Mapper interface and inherit
BaseMapper. At this time, the interface obtains common addition, deletion, modification and query functions, and there is no need to manually write the Mapper configuration file yourself

public interface StudentMapper extends
BaseMapper<Student> {
}

Create the Spring configuration file applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/context/spring-context.xsd
                    http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!-- 数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="root"/>
        <property name="password" value="666666"/>
        <property name="url" value="jdbc:mysql:///school"/>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    </bean>
    
    <!-- Mybatis-Plus提供SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 自动扫描所有mapper接口,将mapper接口生成代理注入spring -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
          p:basePackage="com.example.mpdemo1.mapper"
          p:sqlSessionFactoryBeanName="sqlSessionFactory"/>

</beans>

Test Mapper method

import com.example.mpdemo1.pojo.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class MpTest {
    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void testFindAll(){
        Student students = studentMapper.selectById(3);
        System.out.println(students);
    }
}

Test Results: 

OK, exactly the same as the database.

3. SpringBoot integrates MyBatisPlus

Next we use MyBatisPlus in the SpringBoot project

Create a SpringBoot project and add MyBatisPlus starting dependency

    <dependencies>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.0</version>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

Configure the data source in the SpringBoot configuration file

# 配置数据源
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:///school?serverTimezone=UTC
    username: root
    password: 666666

 Create entity class

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private Integer id;
    private String name;
    private String email;
    private String gender;
    private Integer age;
}

Create Mapper interface.
When using MyBatisPlus, after writing the Mapper interface, there is no need to manually write CRUD methods, and there is no need to manually write the SQL statements corresponding to each method in the Mapper mapping file. Therefore, in MyBatisPlus, you only need to create a Mapper interface and inherit BaseMapper. At this time, the interface has the common addition, deletion, modification and query functions, and there is no need to manually write the Mapper configuration file yourself

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.mpdemo2.pojo.Student;

public interface StudentMapper extends BaseMapper<Student> {
}

Add the @MapperScan annotation to the SpringBoot startup class to scan the Mapper folder

@MapperScan("com.example.mpdemo2.mapper")

Test Mapper method

@SpringBootTest
class Mpdemo2ApplicationTests {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void testFind() {
        Student student = studentMapper.selectById(1);
        System.out.println(student);
    }
}

The running results are very clear.​ 

Guess you like

Origin blog.csdn.net/qq_53317005/article/details/134621573