SpringBoot - Dao integrates MybatisPlus
In this section, learn how to integrate MybatisPlus with SpringBoot.
1. Introduction to mybatisplus
MyBatis plus (MP for short) is an enhancement tool for MyBatis. On the basis of MyBatis, it only makes enhancements and does not change. It is born to simplify development and improve efficiency.
Mybatis plus website - Introduction
characteristic:
- No invasion: it is only enhanced without change, and its introduction will not affect the existing project, which is as smooth as silk
- Low loss: the basic CURD will be injected automatically upon startup, with basically no loss of performance and direct object-oriented operation
- Powerful crud operation: built in general Mapper and general Service, most CRUD operations of a single table can be realized only through a small number of configurations, and there is a powerful condition constructor to meet various use requirements
- Support Lambda formal call: it is convenient to write various query conditions through Lambda expression, and there is no need to worry about wrong fields
- Support automatic generation of primary key: support up to 4 primary key strategies (including distributed unique ID generator - Sequence), which can be configured freely to perfectly solve the primary key problem
- Support ActiveRecord mode: support ActiveRecord formal calls. Entity classes only need to inherit Model classes to perform powerful CRUD operations
- Support custom global general operations: support global general method injection (Write once, use anywhere)
- Built in code generator: code or Maven plug-in can be used to quickly generate Mapper, Model, Service and Controller layer code, support template engine, and more custom configurations 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 plug-in 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 to quickly find out slow queries
- Built in global interception plug-in: it provides intelligent analysis and blocking of full table delete and update operations, and can also customize interception rules to prevent misoperation
Mybatis plus website - features
2. Import MybatisPlus module starter
2.1 importing starter
Maven:
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.4</version> </dependency>
2.2 analysis of import dependencies
Analyze the dependencies introduced after importing the MybatisPlus module starter:
com.baomidou:mybatis-plus-boot-starter:3.4.3.4 │ ├── com.baomidou:mybatis-plus:3.4.3.4 (MybatisPlus package) │ │ │ └── com.baomidou:mybatis-plus-extension:3.4.3.4 │ │ │ ├── com.baomidou:mybatis-plus-core:3.4.3.4 │ │ │ │ │ ├── com.baomidou:mybatis-plus-annotation:3.4.3.4 │ │ │ │ │ ├── com.github.jsqlparser:jsqlparser:4.2 │ │ │ │ │ └── org.mybatis:mybatis:3.5.7 (Mybatis) │ │ | └── org.mybatis:mybatis-spring:2.0.6 (Mybatis And Spring Integration package) | ├── org.springframework.boot:spring-boot-autoconfigure:2.4.5 (SpringBoot Auto configuration package) | └── org.springframework.boot:spring-boot-starter-jdbc:2.4.5 (JDBC Module initiator) │ ├── org.springframework.boot:spring-boot-starter:2.4.5 (Parent initiator) │ ├── com.zaxxer:HikariCP:3.4.5 (Hikari data source(Connection pool)) │ └── org.springframework:spring-jdbc:5.3.6 (SpringJDBC modular)
MybatisPlus module starter introduces Mybatis, Mybatis Spring integration package and Spring JDBC module for us, so don't introduce these dependencies again later to avoid problems caused by version differences.
3. Analyze the principle of automatic configuration
Analyze the spring.factories of MybatisPlus module initiator mybatis plus boot starter:
# Auto Configure org.springframework.boot.env.EnvironmentPostProcessor=\ com.baomidou.mybatisplus.autoconfigure.SafetyEncryptProcessor org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.baomidou.mybatisplus.autoconfigure.IdentifierGeneratorAutoConfiguration,\ com.baomidou.mybatisplus.autoconfigure.MybatisPlusLanguageDriverAutoConfiguration,\ com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration
There are three autoconfiguration classes:
name | effect |
---|---|
IdentifierGeneratorAutoConfiguration | ID generator auto configuration class |
MybatisPlusLanguageDriverAutoConfiguration | MybatisPlus dynamic SQL language driven automatic configuration class |
MybatisPlusAutoConfiguration | MybatisPlus auto configuration class |
Simply analyze the Mybatis automatic configuration class. The automatic configuration class creates and injects SqlSessionFactory and SqlSessionTemplate for us.
And automatically scan Mapper, link them to SqlSessionTemplate and register them with Spring.
The Mybatis automatic configuration class uses MybatisPlusProperties as the configuration parameter class through the @ EnableConfigurationProperties annotation,
The configuration node is mybatis plus, and the common configuration attributes are as follows (for a complete list, see Mybatis plus - configuration ):
attribute | Configuration node | effect |
---|---|---|
configLocation | mybatis-plus.config-location | Location of the XML configuration file for Mybatis |
mapperLocations | mybatis-plus.mapper-locations | XML configuration file location corresponding to Mapper |
Maperlocations has a default value of classpath*:/mapper/**/*.xml, which will automatically scan all XML configuration files under the mapper package under the classpath of any package.
4. MybatisPlus operation
MybatisPlus is used in almost the same way as native Mybatis, but we can use the enhancements in MybatisPlus for more efficient development.
4.1 CRUD operation of persistence layer
MybatisPlus provides a basemapper < T > interface. T is generic. This interface simply encapsulates the CRUD function. Mapper can obtain the CRUD function without writing an XML configuration file after inheriting this interface (see the full instructions for details) Mybatis plus - crud interface ):
Write a simple Mapper test:
@Mapper // Mapper interface inherits BaseMapper interface and generically uses the entity class for CRUD operation public interface AccountMapper extends BaseMapper<Account> { // Use the CRUD function provided by BaseMapper }
Write the control layer for testing (business layer code will not be written here for demonstration):
@RestController public class AccountController { private AccountMapper mapper; @Autowired public void setMapper(AccountMapper mapper) { this.mapper = mapper; } /** * Get all account records * * @return All account records */ @GetMapping("/all") public Object getAll() { // Here, you need to pass in the Wrapper as the condition constructor. null means that there are no conditions. Get all the conditions return mapper.selectList(null); } }
Send / all request test, test result:
[ { "id": 1, "name": "Zhang San", "money": 1000.0 }, { "id": 2, "name": "Li Si", "money": 2000.0 } ]
4.2 business layer CRUD operation
MybatisPlus provides iservice < T > interface. T is generic. This interface further encapsulates CRUD operations. After inheriting this interface, Service class can directly obtain crud functions (see full instructions for details) Mybatis plus - crud interface ):
Write a simple business layer interface test:
// The business layer interface inherits the IService interface and generically uses the entity class for business processing public interface AccountService extends IService<Account> { // Use the CRUD function provided by IService }
MybatisPlus provides serviceimpl < m extensions basemapper < T >, t >, M is the Mapper interface that inherits basemapper < T >, and t is generic. This class implements the IService interface. Write the business layer implementation class with the business layer interface:
@Service // The business layer implementation class inherits the business layer interface and ServiceImpl public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService { // Use the CRUD function provided by IService }
Write the control layer for testing:
@RestController public class AccountController { private AccountService service; @Autowired public void setService(AccountService service) { this.service = service; } /** * Get all account records * * @return All account records */ @GetMapping("/all") public Object getAll() { return service.list(); } }
Send / all request test, test result:
[ { "id": 1, "name": "Zhang San", "money": 1000.0 }, { "id": 2, "name": "Li Si", "money": 2000.0 } ]
4.3 paging query and paging plug-in
MybatisPlus provides PaginationInnerInterceptor paging plug-in. We can use the plug-in to realize simple paging functions.
Usage of paging plug-in: register with Spring container using MybatisPlusInterceptor Interceptor:
@Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // The constructor can specify the database type. MySQL database is used here interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }
Use the page < T > paging model in the control layer for paging:
@GetMapping("/list") public String accountList(Model model, @RequestParam(value = "pageNum", defaultValue = "1")int pageNum) { // Create a paging model and pass in the parameters of the construction method: current page and number of entries per page Page<Account> pageModel = new Page<>(pageNum, 3); // Receive query results Page<Account> pageResult = service.page(pageModel); // Put query results into implicit model model.addAttribute("page", pageResult); // Go to results page return "accountList"; }
Write a simple page with thymeleaf to test the paging function:
Effect display: