MyBatis-Plus entry case
Disclaimer: Without permission, it is forbidden to reproduce in any form. If you want to quote, please mark the link address. The full text is 6873 words in total, and it takes about 3 minutes to read
. For more learning content, please follow my personal public account: Programmer who doesn't understand development
1. Introduction to MyBatis-Plus
1 Introduction
MyBatis-Plus (MP for short) is an enhancement tool of MyBatis , which only enhances and does not change on the basis of MyBatis , and is born to simplify development and improve efficiency .
2. Features
- No intrusion : only enhancement and no change, the introduction of it will not affect the existing project, as smooth as silk
- Low loss : the basic CURD will be automatically injected when it is started, the performance is basically lossless, and the object-oriented operation is directly performed
- Powerful CRUD operations : built-in general Mapper and general Service, most of the CRUD operations on a single table can be realized with only a small amount of configuration, and there is a powerful condition constructor to meet various usage needs
- Support Lambda form call : through Lambda expressions, it is convenient to write various query conditions, no need to worry about field typos
- Supports automatic primary key generation : supports up to 4 primary key strategies (including a distributed unique ID generator - Sequence), which can be freely configured to perfectly solve the primary key problem Support ActiveRecord mode: support ActiveRecord form calls, entity classes only need to inherit the Model class Capable of powerful CRUD operations
- Support custom global general operations : support global general method injection ( Write once, use anywhere )
- Built-in code generator : use code or Maven plug-ins to quickly generate Mapper, Model, Service, and Controller layer codes, support template engines, and have a lot of custom configurations waiting for you to use
- Built-in paging plug-in : Based on MyBatis physical paging, developers don't 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 : supports 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, which can quickly find out slow queries
- Built-in global interception plug-in : Provides intelligent analysis and blocking of delete and update operations on the entire table, and can also customize interception rules to prevent misoperations
3. Support database
Any database that can use MyBatis for CRUD and supports standard SQL, the specific support is as follows
- MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss , ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb
- Dameng Database, Xugu Database, Renmin University Jincang Database, Nanda General (Huaku) Database, Nanda General Database, Shentong Database, Hangao Database
4. Framework structure
5. Code and document address
Official address: http://mp.baomidou.com
Code release address:
Github: https://github.com/baomidou/mybatis-plus
Gitee: https://gitee.com/baomidou/mybatis-plus
Document release address: https://baomidou.com/pages/24112f
2. Introductory case
1. Development environment
tool | Version |
---|---|
IDE | idea2021.3.3 |
JDK | Java8 |
build tool | maven 3.8.5 |
MySQL version | MySQL 8.0.28 |
Spring Boot | 2.7.1 |
MyBatis-Plus | 3.5.1 |
2. Build database and table
CREATE DATABASE `mybatis_plus` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
use `mybatis_plus`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
adding data
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]');
3. Create a Spring Boot project
a>Initialization project
Use Spring Initializr to quickly initialize a Spring Boot project
b>Introduce dependencies
pom.xml
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.jerry</groupId>
<artifactId>mybatisplus</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatisplus</name>
<description>mybatisplus</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4. Write code
a> Configure application.yml or application.properties
application.properties
#spring.datasource.type=com.zaxxer.hikari.HikariDataSource
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
#spring.datasource.username=root
#spring.datasource.name=root
application.yml
spring:
# 配置数据源信息
datasource:
# 配置数据源类型
type: com.zaxxer.hikari.HikariDataSource
# 配置连接数据库的各个信息
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
username: root
password: root
Notice:
1. Driver class driver-class-name
spring boot 2.0 (built-in jdbc5 driver), the driver class uses:
driver-class-name: com.mysql.jdbc.Driver
Spring boot 2.1 and above (built-in jdbc8 driver), the driver class uses:
driver-class-name: com.mysql.cj.jdbc.Driver
Otherwise, there will be WARN information when running the test case
2. Connection address url MySQL5.7 version url:
jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
URL of MySQL8.0 version:
jdbc:mysql://localhost:3306/mybatis_plus? serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
Otherwise, running the test case reports the following error:
java.sql.SQLException: The server time zone value ‘Öйú±ê׼ʱ¼ä’ is unrecognized or represents more
b>Add entity
package com.jerry.mybatisplus.pojo;
import lombok.Data;
/**
* ClassName: User
* Package: com.jerry.mybatisplus.pojo
* Description:
*
* @Author jerry_jy
* @Create 2023-02-09 16:52
* @Version 1.0
*/
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
c> add mapper
BaseMapper is a template mapper provided by MyBatis-Plus, which contains basic CRUD methods, and the generic type is the entity type of the operation
package com.jerry.mybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jerry.mybatisplus.pojo.User;
import org.apache.ibatis.annotations.Mapper;
/**
* ClassName: UserMapper
* Package: com.jerry.mybatisplus.mapper
* Description:
*
* @Author jerry_jy
* @Create 2023-02-09 16:59
* @Version 1.0
*/
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
d> start class
Add the @MapperScan annotation to the Spring Boot startup class to scan the mapper package
@MapperScan("com.jerry.mybatisplus.mapper")
@SpringBootApplication
public class MybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args);
}
}
e> test
package com.jerry.mybatisplus;
import com.jerry.mybatisplus.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* ClassName: MybatisPlusTest
* Package: com.jerry.mybatisplus
* Description:
*
* @Author jerry_jy
* @Create 2023-02-09 17:04
* @Version 1.0
*/
@SpringBootTest
public class MybatisPlusTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectList(){
userMapper.selectList(null).forEach(System.out::println);
}
}
Notice:
IDEA reports an error at userMapper because the injected object cannot be found, because the class is dynamically created, but the program can be executed correctly.
In order to avoid error reporting, you can add the @Repository annotation to the mapper interface
f> add log
Configure log output in application.yml
# 配置MyBatis日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
–end–