content
6.2, create database and table
6.3. Create a SpringBoot project
6.3.2. Introducing dependencies
6.4.1. Configure application.yml
6.4.3. Startup class (main program class)
1 Introduction
MyBatis-Plus ( MP for short ) is an enhancement tool for MyBatis . It only enhances and does not change on the basis of MyBatis . It is born to simplify development and improve efficiency .
vision
Our vision is to become the best partner of MyBatis , just like 1P , 2P in Contra, with friends, the efficiency is doubled.
2. Features
-
Non-invasive : only make enhancements without changing, introducing it will not affect existing projects, smooth as silk
-
Low loss : Basic CURD is automatically injected at startup, performance is basically lossless, and direct object-oriented operation
-
Powerful CRUD operations : built-in general mapper and general service, most CRUD operations on a single table can be realized with only a small amount of configuration, and more powerful conditional constructors to meet various usage needs
-
Support Lambda form invocation : Through Lambda expressions, you can easily write various query conditions, and you don't need to worry about writing wrong fields.
-
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 call, entity class can perform powerful CRUD operations only by inheriting Model class
-
Support custom global general operations : support global general method injection ( Write once, use anywhere )
-
Built-in code generator : Use code or Maven plugin to quickly generate Mapper , Model , Service , Controller layer code, support template engine, and more custom configurations waiting 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 plugin 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, which can quickly identify 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 misoperation
3. Support database
Any database that can use MyBatis for CRUD and supports standard SQL, the specific support is as follows, if you do not see the paging part of the tutorial PR your support in the list below.
-
MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb
-
Dameng Database, Xugu Database, NPC Jincang Database, Nanda General (Huaku) Database, Nanda General Database, Shentong Database, Hangao Database
4. Frame structure
5. Code and document address
-
Official address: Redirect
-
Code release address:
-
Document release address: Introduction | MyBatis-Plus
6. Introductory case
6.1. Development environment
IDE : idea 2021.2.1
JDK:JDK8
Build tool: maven 3.6.1
MySQL version: MySQL 5.7
Spring Boot:2.6.6
MyBatis-Plus:3.5.1
6.2, create database and table
6.2.1. Create a table
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;
6.2.2. Add 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]');
6.3. Create a SpringBoot project
6.3.1. Initialization project
Use Spring Initializer to quickly initialize SpringBoot projects without checking components
6.3.2. Introducing dependencies
<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>
6.4, write code
6.4.1. Configure application.yml
Note:1. Driver class driver-class-nameSpring boot 2.0 (built-in jdbc5 driver), the driver class uses: driver-class-name: com.mysql.jdbc.DriverSpring boot 2.1 and above (built-in jdbc8 driver), driver class use: driver-class-name: com.mysql.cj.jdbc.DriverOtherwise, there will be WARN information when running the test case2 , the connection address urlThe URL recommendations for MySQL 5.7 are as follows :jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=falseThe url of MySQL 8.0 is recommended as follows (set the time zone):jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=falseOtherwise running the test case reports the following error:java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more
spring:
# 配置数据源信息
datasource:
# 配置数据源类型
type: com.zaxxer.hikari.HikariDataSource
# 配置连接数据库的各个信息
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
username: root
password: zyj123
6.4.2. Add entity
@Data
@AllArgsConstructor
public class User {
private long id;
private String name;
private Integer age;
private String email;
}
6.4.3. Startup class (main program class)
@SpringBootApplication
@MapperScan("com.zyj.mapper") //扫描mapper接口所在的包
public class MyBatisPlusProjectApplication {
public static void main(String[] args) {
SpringApplication.run(MyBatisPlusProjectApplication.class, args);
}
}
6.4.4. Add mapper interface
@Mapper
//@Repository //将该类或接口标识为持久层组件
public interface UserMapper extends BaseMapper<User> {
}
6.4.5. Test
Note: 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 errors, you can add @Repository or @Mapper annotations to the mapper interface
@SpringBootTest
public class MyBatisPlusTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectList(){
// 通过条件构造器查询一个List集合,若没有条件,可以设置参数为null
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
Output result:
User(id=1, name=Jone, age=18, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=3, name=Tom, age=28, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=5, name=Billie, age=24, [email protected])
6.4.6. Add log function
Configure open in application.yml
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #添加日志功能,StdOutImpl是mybatis-plus自带的
The log output is as follows, you can view the SQL statement:
==> Preparing: SELECT id,name,age,email FROM user
==> Parameters:
<== Columns: id, name, age, email
<== Row: 1, Jone, 18, [email protected]
<== Row: 2, Jack, 20, [email protected]
<== Row: 3, Tom, 28, [email protected]
<== Row: 4, Sandy, 21, [email protected]
<== Row: 5, Billie, 24, [email protected]
<== Total: 5