MyBatisPlus entry case and introduction
- 1. MyBatisPlus entry case and introduction
-
- 1.1 Getting Started Case
-
- Step 1: Create database and tables
- Step 2: Create a SpringBoot project
- Step 3: Tick Configure using technology
- Step 4: pom.xml completion dependency
- Step 5: Add MP related configuration information
- Step 6: Create entity classes based on database tables
- Step 7: Create Dao interface
- Step 8: Write the bootstrap class
- Step 9: Write the test class
- 1.2 Introduction to MybatisPlus
1. MyBatisPlus entry case and introduction
In this section, let's learn about the introductory case and introduction of MyBatisPlus. This is different from other courses. Other courses first introduce concepts and then write introductory cases. As for the learning of MyBatisPlus, we adjusted the order. The main reason is that MyBatisPlus mainly simplifies MyBatis. So we first understand where it is simplified, and then learn what it is and what it does for us.
1.1 Getting Started Case
-
MybatisPlus (MP for short) is an enhanced tool developed based on the MyBatis framework, designed to simplify development and improve efficiency.
-
development method
- Using MyBatisPlus based on MyBatis
- Using MyBatisPlus based on Spring
- Using MyBatisPlus based on SpringBoot
We have just finished learning SpringBoot. It can quickly build a Spring development environment to integrate other technologies. It is very simple to use. For MP learning, we also build learning based on SpringBoot.
Before learning, let's review the development process of SpringBoot integrating Mybatis:
-
Create a SpringBoot project
-
Check the technology used in the configuration to automatically add the starting dependency package
-
Set dataSource related properties (JDBC parameters)
-
Define data layer interface mapping configuration
We can refer to the above implementation steps to integrate SpringBoot into MyBatisPlus for quick implementation. The specific implementation steps are:
Step 1: Create database and tables
create database if not exists mybatisplus_db character set utf8;
use mybatisplus_db;
CREATE TABLE user (
id bigint(20) primary key auto_increment,
name varchar(32) not null,
password varchar(32) not null,
age int(3) not null ,
tel varchar(32) not null
);
insert into user values(1,'Tom','tom',3,'18866668888');
insert into user values(2,'Jerry','jerry',4,'16688886666');
insert into user values(3,'Jock','123456',41,'18812345678');
insert into user values(4,'传智播客','itcast',15,'4006184000');
Step 2: Create a SpringBoot project
Step 3: Tick Configure using technology
illustrate:
- Since MP has not been included in the system built-in configuration of idea, it cannot be directly selected to join, and it needs to be manually configured and added in pom.xml
Step 4: pom.xml completion dependency
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
illustrate:
-
The druid data source can be added or not. SpringBoot has a built-in data source that can be configured to use the Druid data source
-
It can be seen from the dependency relationship of MP that MyBatis and MyBatis have been integrated into the jar package of Spring through dependency transfer, and we do not need to add additional related jar packages of MyBatis
Step 5: Add MP related configuration information
The default generated by resources is the properties configuration file, which can be replaced with a yml file, and the relevant information of the database connection is configured in the file:application.yml
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=UTC
username: root
password: root
illustrate:serverTimezone is used to set the time zone, UTC is the standard time zone, which is 8 hours behind our time, so it can be modified asAsia/Shanghai
Step 6: Create entity classes based on database tables
public class User {
private Long id;
private String name;
private String password;
private Integer age;
private String tel;
//setter...getter...toString方法略
}
Step 7: Create Dao interface
@Mapper
public interface UserDao extends BaseMapper<User>{
}
Step 8: Write the bootstrap class
@SpringBootApplication
//@MapperScan("com.itheima.dao")
public class Mybatisplus01QuickstartApplication {
public static void main(String[] args) {
SpringApplication.run(Mybatisplus01QuickstartApplication.class, args);
}
}
Note: If the Dao interface is to be scanned by the container, there are two solutions:
- Solution 1: Add annotations to the Dao interface
@Mapper
and ensure that Dao is in the package where the bootstrap class is located or its subpackage- The disadvantage of this solution is that annotations need to be added to each Dao interface
- Solution 2: Add annotations to the boot class
@MapperScan
, whose attribute is the package of the Dao to be scanned- The advantage of this solution is that it only needs to be written once, and all Dao interfaces under the specified package can be scanned,
@Mapper
so it does not need to be written.
- The advantage of this solution is that it only needs to be written once, and all Dao interfaces under the specified package can be scanned,
Step 9: Write the test class
@SpringBootTest
class MpDemoApplicationTests {
@Autowired
private UserDao userDao;
@Test
public void testGetAll() {
List<User> userList = userDao.selectList(null);
System.out.println(userList);
}
}
illustrate:
What is the reason for the red line prompt below when userDao is injected?
-
UserDao is an interface and cannot instantiate objects
-
Only after the server starts the IOC container initialization, the proxy object of the DAO interface is created by the framework to inject
-
Now the server is not started, so the proxy object has not been created, and IDEA cannot find the corresponding object injection, so the prompt reports red
-
Once the service is started, its proxy object can be injected, so the error message does not affect normal operation.
View running results:
Compared with the previous integration of MyBatis, you will find that we don't need to write methods and SQL statements in the DAO interface, just inherit BaseMapper
the interface. Overall, it is much simplified.
1.2 Introduction to MybatisPlus
MyBatisPlus (MP for short) is an enhanced tool developed based on the MyBatis framework, designed toSimplify development and increase efficiency
Through the case just now, I believe that everyone can appreciate the advantages of simplifying development and improving efficiency.
The official website of MyBatisPlus is:https://mp.baomidou.com/
illustrate:
In the current page, this line has been deleted, and if you visit it now, you https://mybatis.plus
will find that you cannot access it. There are many possibilities for us to guess, so you can use the URL of baomidou to visit.
There is a picture in the official document that many friends are familiar with:
From this picture, we can see that MP aims to be the best partner of MyBatis, not to replace MyBatis, so it can be understood that MP is a set of enhanced tools for MyBatis, which is developed on the basis of MyBatis. Although we use MP But the bottom layer is still MyBatis, which means we can also write MyBatis content in MP.
For MP learning, you can refer to the official documents for learning, which contain detailed code cases.
Features of MP:
- No intrusion: only enhancement without change, no impact on existing projects
- Powerful CRUD operation: Built-in general Mapper, a small amount of configuration can realize single-table CRUD operation
- Support Lambda: Write query conditions without worrying about field errors
- Supports automatic generation of primary keys
- Built-in pagination plugin
- ……
Study Notes from Dark Horse Programmer
By – Suki 2023/4/6