I. Initial MyBatis-Plus
@
- I. Initial MyBatis-Plus
- 1. Overview of MyBatis-Plus
- 2. Getting Started Configuring Your First MyBatis-Plus Case
-
3. Additional notes:
-
3.1 Introduction to the Generic Mapper Interface
-
3.1.1 The Mapper interface "add, delete, change"
- 3.1.1.1 Querying all records
- 3.1.1.2 Insertion of a piece of data
- 3.1.1.3 Deleting a piece of data
- 3.1.1.4 Updating a piece of data
- 3.1.1.5 Querying a piece of data
-
3.1.1 The Mapper interface "add, delete, change"
-
3.2 Introduction to the Common Service Interface
-
3.2.1 Service Interface "Add, Delete, Change"
- 3.2.1.1 Adding a record
- 3.2.1.2 Deleting a record
- 3.2.1.3 Modifying a record
- 3.2.1.4 Querying a record
-
3.2.1 Service Interface "Add, Delete, Change"
-
3.3 Customized methods
- 3.3.1 Customizing Mapper Interface Methods
-
3.1 Introduction to the Generic Mapper Interface
- 4. Summary:
- 6. Finally:
1. Overview of MyBatis-Plus
Before learning about MyBatis -Plus, we can start with a brief, slight, review of some of the issues with the MyBatis framework:
Here is just a brief review, for more details about MyBatis you can move to: ✏️✏️✏️MyBatis_ChinaRainbowSea's Blog - CSDN Blogs
Let's think briefly about how efficiently the MyBatis framework can be developed.
Development efficiency is also how fast we can develop with this framework and whether it is simple and easy to use. Thinking about it from this perspective, whenever we need to write a SQL requirement, we need to do a few steps:
- The Mapper interface provides an abstract method.
- The mapping profile for the Mapper interface provides the corresponding tags and SQL statements.
- Relying on Mapper Instance Objects in Service
- Calling Methods in a Mapper Instance
- Relying on Service Instance Objects in the Controller
- Calling Methods in a Service Instance
Through the above findings, for a SQL requirement, whether it is a single table or multiple tables, we do need to complete the steps as above in order to realize the development of the SQL requirement.
But in development, there are operations that are done through logic, and these generalized logics can be simplified, for example:
- For dao, is it possible for the framework to help us provide a good single-table Mapper abstract method, and the corresponding SQL implementation, without the need for programmers to implement these.
- For service, using the framework can help us directly provide a good serivce of abstract methods, and the corresponding implementation, do not need programmers to implement these.
- Some other operations required in enterprise development
Analysis here we find that in fact, the core framework has not changed, the dependency is still Mybatis, but we want to MyBatis for some encapsulation and optimization, so that he is more useful, more easy to use.
So: MyBatis Plus It's here, an enhancement tool for MyBatis.
MybatisPlus, from the name, we find that he and Mybatis look alike, in fact, MybatisPlus is the twin brother of Mybatis. Learning MyBatis-Plus First of all, let's take a look at its official website address is:/
MyBatis-Plus (opens new window)(MP for short) is aMyBatis (opens new window)Enhancement tools in MyBatis on the basis of only enhancements do not change , in order to simplify the development , improve efficiency and born .
vision (of the future)
Our vision is to be the best partner for MyBatis, just as theContra The 1P and 2P in the middle, base pairing, doubling the efficiency.
Characterization of MyBatis-Plus:
- non-intrusive: Enhancement only, no change, introduction of it will not affect the existing works, silky smooth
- low loss: Basic CURD is automatically injected at startup, with virtually no performance loss, and direct object-oriented operation.
- Powerful CRUD operations: Built-in generic Mapper, generic Service, only through a small amount of configuration can realize most of the CRUD operations of a single table, and more powerful conditional constructor, to meet the needs of various types of use
- Support for Lambda form callsLambda Expressions: Lambda Expressions make it easy to write all kinds of queries without having to worry about misspelled fields.
- Supports auto-generation of primary keysSupport for up to 4 primary key policies (with distributed unique ID generator - Sequence), freely configurable, perfect for solving primary key problems.
- ActiveRecord mode support: Support ActiveRecord form call, entity class only need to inherit Model class can be powerful CRUD operation.
- Support for customizing global generic operations: support global generic method injection (Write once, use anywhere)
- Built-in code generator: Using code or Maven plug-ins can quickly generate Mapper, Model, Service, Controller layer code, support for template engines, 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 the specific operation, configure the plugin, write paging equivalent to ordinary List query
- Pagination plugin supports multiple databasesSupport MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and many other databases.
- Built-in performance analysis plug-in: SQL statement and its execution time can be output, it is recommended that the development of the test to enable the function, can quickly find out the slow query
- Built-in global blocking pluginProvide intelligent analysis and blocking of all table delete and update operations, as well as customizable blocking rules to prevent misoperation.
Framework structure of MyBatis-Plus:
What is the Mybatis framework? He is a persistence layer framework designed to simplify the development of the persistence layer. Here we will use springboot to integrate Mybatis and realize the Mybatis framework.
Special Note: This is a step-by-step procedure for creating a project in IDEA 2021:
We start by creating an empty project
The project name is mp
Creating a springboot module
Here we select the springboot 2.7.8 version and leave the dependencies unchecked, and then add them manually by adding the
Special Note: The following is the operating configuration for IDEA 2024.
2. Getting Started Configuring Your First MyBatis-Plus Case
Step one: Create database mybatisplus
These test tables, is from the MyBatis-Plus official teaching content, you can also move to see: ✏️✏️✏️/getting-started/
There is a User table with the following table structure:
id | name | age | |
---|---|---|---|
1 | Jone | 18 | test1@ |
2 | Jack | 20 | test2@ |
3 | Tom | 28 | test3@ |
4 | Sandy | 21 | test4@ |
5 | Billie | 24 | test5@ |
The corresponding database Schema script is as follows:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`
(
id BIGINT NOT NULL COMMENT 'primary keyID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT 'name and surname',
age INT NULL DEFAULT NULL COMMENT '(a person's) age',
email VARCHAR(50) NULL DEFAULT NULL COMMENT 'inbox',
PRIMARY KEY (id)
);
The corresponding database Data script is as follows:
DELETE FROM `user`;
INSERT INTO `user` (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@'),
(2, 'Jack', 20, 'test2@'),
(3, 'Tom', 28, 'test3@'),
(4, 'Sandy', 21, 'test4@'),
(5, 'Billie', 24, 'test5@');
Step two: Introduce the dependencies and configure the jar dependencies we need in the file.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0" xmlns:xsi="http:///2001/XMLSchema-instance"
xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId></groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId></groupId>
<artifactId>mp02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mp02</name>
<description>mp02</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<>8</>
</properties>
<dependencies>
<dependency>
<groupId></groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId></groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- spring boot web dependencies-->
<dependency>
<groupId></groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mysql 驱动dependencies-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok 的dependencies-->
<dependency>
<groupId></groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- druid-->
<dependency>
<groupId></groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!-- mybatis-plus 的dependencies-->
<dependency>
<groupId></groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId></groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</project>
Special Note: Here we, change Spring boot to:
2.5.3
Version.
MyBatis-Plus includes a dependency on MyBatis. So, by introducing MyBatis-Plus, you are also introducing MyBatis.
Step Three: Write the scene starter for this project/module:
Step Four: Create the corresponding entity class based on the data table:
package ;
import ;
import ;
import ;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
Step Five: Switching the database connection pool to Druid. Here we write the configuration class to switch the database connection pool.
- Under the resoucre class path, create a file named
configuration file, which writes the configuration information for connecting to the database.
spring:
datasource:
driver-class-name:
url: jdbc:mysql://localhost:3306/mybatisplus?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
username: root
password: MySQL123
- Write a configuration class to switch the database to Druid
package ;
import ;
import ;
import ;
import ;
import ;
/**
* Configuration switching,Druid database connection pool
*/
@Configuration // Flag Configuration Class
public class DruidDataSourceConfig {
@Bean // (indicates passive-voice clauses) Spring ioc Containers managed up
@ConfigurationProperties(value = "")
public DataSource getDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
return druidDataSource;
}
}
Special Note: For details on switching database connection pools in spring boot, you can move to: ✏️✏️✏️Spring Boot Integration with Druid and Monitoring with Druid - CSDN Blogs
Test: See if we successfully switched to Druid database connection pooling.
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@SpringBootTest(classes = ) // Spring Boot Tests in the middle,must have Project start-up scenarios,Otherwise you can't test for errors.
class Mp02ApplicationTests {
@Resource
private JdbcTemplate jdbcTemplate;
@Test
void contextLoads() {
(().getClass());
}
}
Step Six: All the ones after that.Corresponding to MyBatis-Plus The content of the focus on the content of the
Writing the Mapper Interface
package ;
import ;
import ;
import ;
@Mapper // (indicates passive-voice clauses)Spring Boot scan
public interface UserMapper extends BaseMapper<User> {
}
Our own Mapper interface extends (inherits) the BaseMapper interface and has the methods of that interface.
Step Seven: Writing Service Interfaces
package ;
import ;
import ;
import ;
public interface UserService extends IService<User> {
// When the methods provided in the IService do not meet our business needs, // we can customize the methods.
// We can customize the methods.
// Customized methods
List<User> selectAll();
}
Step Eight: Write ServiceImpl
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User>
implements UserService {
//@Resource
@Autowired // automated assembly
private UserMapper userMapper;
// For custom methods of the,rewrite the implementation
@Override
public List<User> selectAll() {
return (null);
}
}
The relationship between them is structured as follows:
Step Nine:Write the Controller controller:
package ;
import ;
import ;
import ;
import ;
import ;
import ;
@RestController
public class UserController {
@Resource
private UserService userService;
@GetMapping(value = {"/selectList"})
public List<User> selectList() {
return ();
}
}
Step 11 : Open a browser and run the test.
3. Additional notes:
3.1 Introduction to the Generic Mapper Interface
With regard to the Mapper interface, as we have seen before, the Mapper interface we wrote inherits from our own BaseMapper interface, which provides a number of single-tableadd, delete and check In the introductory case, we test all the operations of the query. We introduce some simpleMapper The methods in the interface, mainly feel. Mapper interface for a single table of the operation of the addition, deletion, modification and checking are involved in some more advanced operations.
3.1.1 The Mapper interface "add, delete, change"
3.1.1.1 Querying all records
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@SpringBootTest(classes = ) // Spring Boot Tests in the middle,must have Project start-up scenarios,Otherwise you can't test for errors.
class Mp02ApplicationTests {
@Resource
private UserMapper userMapper;
// Query all
@Test
void selectList() {
List<User> users = (null);
for (User user : users) {
(user);
}
}
}
3.1.1.2 Insertion of a piece of data
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@SpringBootTest(classes = ) // Spring Boot Tests in the middle,must have Project start-up scenarios,Otherwise you can't test for errors.
class Mp02ApplicationTests {
@Resource
private UserMapper userMapper;
// Simple Additions
@Test
void insert() {
User user = new User();
(6L);
(18);
("Lihua");
("test6@");
(user);
}
}
3.1.1.3 Deleting a piece of data
import ;
import ;
import ;
import ;
import ;import ;import ;import ;import
import ;import ;import ;import ;import
import ;
import ;import ;import ;import ;import
import ;
@SpringBootTest(classes = ) // Spring Boot when the test, you must have the project's startup scenario, otherwise you can not test the report errors
class Mp02ApplicationTests {
class Mp02ApplicationTests { @Resource
private UserMapper userMapper;
// Simple deletion
void deleteOne() { void deleteOne() { void deleteOne()
void deleteOne() {
(4L).
}
}
3.1.1.4 Updating a piece of data
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@SpringBootTest(classes = ) // Spring Boot Tests in the middle,must have Project start-up scenarios,Otherwise you can't test for errors.
class Mp02ApplicationTests {
@Resource
private UserMapper userMapper;
// simple update
@Test
void updateById() {
User user = new User();
(2L);
(18);
("Li Hua (232-300), Western Jin writer, poet and politician");
("lihua@");
(user);
}
}
3.1.1.5 Querying a piece of data
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@SpringBootTest(classes = ) // Spring Boot Tests in the middle,must have Project start-up scenarios,Otherwise you can't test for errors.
class Mp02ApplicationTests {
@Resource
private UserMapper userMapper;
// simple query
@Test
void selectById() {
User user = (6L);
(user);
}
}
3.2 Introduction to the Common Service Interface
In addition to the Mapper interface, MybatisPlus also provides the IService interface and the corresponding implementation of the class ServiceImpl, the implementation of the class has provided a good number of corresponding Service-related methods, in some scenarios, we can directly use the methods provided by the ServiceImpl, the realization of the corresponding functions.
IService interface
The IService interface contains a number of service-related methods for adding, deleting, modifying, and checking.
ServiceImpl implementation class
ServiceImpl implementation class provides the implementation of service-related add, delete, change and check methods.
The UserService interface inherits from the IService interface.
UserServiceImpl class inherits ServiceImpl<UserMapper,User>.
Injecting UserService objects and testing related methods
3.2.1 Service Interface "Add, Delete, Change"
3.2.1.1 Adding a record
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@SpringBootTest(classes = ) // Spring Boot Tests in the middle,must have Project start-up scenarios,Otherwise you can't test for errors.
class Mp02ApplicationTests {
@Autowired
private UserService userService;
// UserService increase
@Test
void insertService() {
User user = new User();
(7L);
(18);
("Tom");
("Tom@");
(user);
}
}
3.2.1.2 Deleting a record
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@SpringBootTest(classes = ) // Spring Boot Tests in the middle,must have Project start-up scenarios,Otherwise you can't test for errors.
class Mp02ApplicationTests {
@Autowired
private UserService userService;
// UserService removing
@Test
void deleteServie() {
(2L);
}
}
3.2.1.3 Modifying a record
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@SpringBootTest(classes = ) // Spring Boot Tests in the middle,must have Project start-up scenarios,Otherwise you can't test for errors.
class Mp02ApplicationTests {
@Autowired
private UserService userService;
// userService modifications
@Test
void updateService() {
User user = new User();
(3L);
(22);
(user);
}
}
3.2.1.4 Querying a record
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@SpringBootTest(classes = ) // Spring Boot Tests in the middle,must have Project start-up scenarios,Otherwise you can't test for errors.
class Mp02ApplicationTests {
@Autowired
private UserService userService;
// UserService consult (a document etc)
@Test
void selectService() {
List<User> users = ();
for (User user : users) {
(user);
}
}
}
3.3 Customized methods
MybatisPlus in addition to providing us with these rich interface methods, for our own needs, you can also write custom interface methods, we write our own SQL statements in the form of the SQL requirements to achieve the desired
3.3.1 Customizing Mapper Interface Methods
Abstract methods are provided in the Mapper interface
package ;
import ;
import ;
import ;
@Mapper // (indicates passive-voice clauses)Spring Boot scan
public interface UserMapper extends BaseMapper<User> {
// Custom Methods
User selectByName(String name);
}
Provide mapping profiles, provide corresponding SQL statements
Note: The corresponding mapped SQL profiles should have the same path/package, as well as the same name, to work.
<?xml version="1.0" encoding="UTF-8"?> <!-- Don't move that.,indicatexmlversions,and the encoding of the read -->
<!DOCTYPE mapper
PUBLIC "-////DTD Mapper 3.0//EN"
"/dtd/">
<mapper namespace="" >
<select resultType="" parameterType="string">
select id,age,name,email
from user
where name = #{value}
</select>
</mapper>
Testing customized Mapper interface methods
import ;
import ;
import ;
import ;
import ;import ;import ;import ;import
import ;import ;import ;import ;import
import ;
import ;import ;import ;import ;import
import ;
@SpringBootTest(classes = ) // Spring Boot when the test, you must have the project's startup scenario, otherwise you can not test the report errors
class Mp02ApplicationTests {
class Mp02ApplicationTests { @Resource
private UserMapper userMapper;
// Test the custom method
@Test
void myMethod() {
User tom = ("Lihua");
(tom).
}
}
4. Summary:
- MyBatis-Plus official website address:/
- MyBatis-Plus (opens new window)(MP for short) is aMyBatis (opens new window)Enhancement tools in MyBatis on the basis of only enhancements do not change , in order to simplify the development , improve efficiency and born .
- Memorize and understand the Mapper and Service interfaces built into MyBatis-Plus.
6. Finally:
"In this final chapter, I would like to express my gratitude to each and every one of my readers. Your attention and responses have been a source of motivation for me to create, and I have drawn endless inspiration and courage from you. I will keep your encouragement in my heart and continue to struggle in other areas. Thanks to you all, we will always meet again at some point."