[Spring Cloud Alibaba] Mybatis Plus persistence layer
1,Mybatis Plus
Mybatis Plus is a domestic persistence layer framework. It is very simple to use here. It should be in Chinese!
Mybatis Plus official website: https://baomidou.com/
Spring Cloud Alibaba integrates in the same way as Spring Boot
- 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 policies (including distributed unique ID generator - Sequence), which can be configured freely and - 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
2. Integrated Mybatis Plus
Create the spring cloud Alibaba mybatis plus module and introduce related dependencies. It is no different from other modules. It is also registered in Nacos
${mybatis-plus-boot-starter.version} ${lombok.version} Version is <mybatis-plus-boot-starter.version>3.4.3</mybatis-plus-boot-starter.version> <lombok.version>1.18.20</lombok.version>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus-boot-starter.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency>
Modify application yml configuration file, in order to facilitate writing, the yml format is used here
# Application configuration server: port: 8006 # Endpoint monitoring management: endpoint: health: show-details: always endpoints: jmx: exposure: include: '*' web: exposure: include: '*' server: port: 9006 spring: # apply name application: name: spring-cloud-alibaba-gateway # data source datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/spring-cloud-alibaba-learn?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true username: root password: 123456 jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 serialization: write-dates-as-timestamps: false # Nacos configuration cloud: nacos: discovery: namespace: sandbox-configuration password: nacos server-addr: localhost:8848 username: nacos # MybatisPlus configuration mybatis-plus: configuration: map-underscore-to-camel-case: true auto-mapping-behavior: full log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath*:mapper/**/*Mapper.xml global-config: # Logical delete configuration db-config: # Before deletion logic-not-delete-value: 1 # After deletion logic-delete-value: 2
Start class addition
@EnableDiscoveryClient
Create control layer
package cn.tellsea.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * User table front end controller * * @author Tellsea * @since 2021-12-28 */ @RestController @RequestMapping("/userInfo") public class UserInfoController { }
Create interface
package cn.tellsea.service; import cn.tellsea.entity.UserInfo; import com.baomidou.mybatisplus.extension.service.IService; /** * User table service class * * @author Tellsea * @since 2021-12-28 */ public interface IUserInfoService extends IService<UserInfo> { }
Create interface implementation class
package cn.tellsea.service.impl; import cn.tellsea.entity.UserInfo; import cn.tellsea.mapper.UserInfoMapper; import cn.tellsea.service.IUserInfoService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * User table service implementation class * * @author Tellsea * @since 2021-12-28 */ @Service public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService { }
Create Mapper
package cn.tellsea.mapper; import cn.tellsea.entity.UserInfo; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * Mapper Interface * * @author Tellsea * @since 2021-12-28 */ public interface UserInfoMapper extends BaseMapper<UserInfo> { }
Under resources/mapper, create mapper xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.tellsea.mapper.UserInfoMapper"> <!-- custom SQL --> </mapper>
Create unit test
package cn.tellsea; import cn.tellsea.entity.UserInfo; import cn.tellsea.service.IUserInfoService; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.ArrayList; import java.util.List; /** * unit testing * * @author Tellsea * @date 2021/12/28 */ @SpringBootTest class SpringCloudAlibabaMybatisPlusApplicationTests { @Autowired private IUserInfoService userInfoService; @Test void contextLoads() { } @Test public void test() { UserInfo entity = new UserInfo(); List<UserInfo> userInfoList = new ArrayList<>(); // newly added userInfoService.save(entity); // Batch add userInfoService.saveBatch(userInfoList); // Update by ID userInfoService.updateById(entity); // Batch update by ID userInfoService.updateBatchById(userInfoList); // Delete by ID userInfoService.removeById(entity.getId()); // Query all userInfoService.list(); // Condition query userInfoService.list(new LambdaQueryWrapper<UserInfo>() .like(UserInfo::getUserName, entity.getUserName())); } }
These codes can be generated at one time through the code generator of Mybatis Plus. This article mainly explains that the use of Mybatis Plus in spring cloud Alibaba is the same as that in Spring Boot. The code generator of Mybatis Plus will be updated in the corresponding module, and specify the use method and customized template