Preface
In this article, Lizhi mainly sorts out the code generation and use of multiple data sources in MyBatis-Plus. The basic operations are relatively simple. There are also detailed tutorials on the official website. Lizhi will sort it out, hoping to help those in need. My little friend~~~
Article directory
3.1 Configuration of multi-data source environment
3.2 Application of multiple data sources
1. General enumeration
When some field values are fixed, such as gender, you can use MyBatis-Plus's general enumeration to achieve this.
Set enumeration class
@EnumValue: Store the value of the attribute annotated with the unlock identifier in the database. If this annotation is not added and enumeration scanning is not enabled, the default value inserted into the database is MALE | FEMALE.
package com.crj.mybatisplus_test.enums;
import com.baomidou.mybatisplus.annotation.EnumValue;
import lombok.Getter;
@Getter
public enum SexEnum {
MALE(1,"男"),
FEMALE(2,"女");
@EnumValue //将注解锁标识的属性的值存储在数据库中
private Integer sex;
private String sexName;
SexEnum(Integer sex, String sexName) {
this.sex = sex;
this.sexName = sexName;
}
}
Set scanning common enumeration in configuration file
mybatis-plus:
#设置扫描通用枚举
type-enums-package: com.crj.mybatisplus_test.enums
Test class
package com.crj.mybatisplus_test;
import com.crj.mybatisplus_test.enums.SexEnum;
import com.crj.mybatisplus_test.mapper.UserMapper;
import com.crj.mybatisplus_test.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class MyBatisPlusEnumTset {
@Autowired
private UserMapper userMapper;
@Test
public void test(){
User user = new User();
user.setName("CRJ");
user.setAge(21);
user.setSex(SexEnum.MALE);
int result = userMapper.insert(user);
System.out.println("result:"+result);
}
}
Entity class
package com.crj.mybatisplus_test.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.crj.mybatisplus_test.enums.SexEnum;
import lombok.*;
//使用Lombok简化开发加上无参构造方法、有参构造
//@NoArgsConstructor
//@AllArgsConstructor
//@Getter
//@Setter
//@EqualsAndHashCode
@Data
@TableName("t_user")
public class User {
@TableId(value = "uid",type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
private SexEnum sex;
}
2. Code Generator
Different from MyBatis' reverse engineering, MyBatis-Plus' code generator can generate control layer, business layer, persistence layer, mapping file and mapper interface through tables.
Add code generator dependencies
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
Quickly generate demos for executing the official website
package com.crj.mybatisplus_test;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.Collections;
public class FastAutoGeneratorTest {
public static void main(String[] args) {
FastAutoGenerator.create("jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&userSSL=false", "username", "password")
.globalConfig(builder -> {
builder.author("CRJ") // 设置作者
.enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir("D://mybatis_plus"); // 指定输出目录
})
.packageConfig(builder -> {
builder.parent("com.crj") // 设置父包名
.moduleName("mybatisplus") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D://mybatis_plus")); // 设置mapperXml生成路径
})
.strategyConfig(builder -> {
builder.addInclude("t_user") // 设置需要生成的表名
.addTablePrefix("t_", "c_"); // 设置过滤表前缀
})
.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}
3. Multiple data sources
Multi-data sources are both dynamic data sources. As project development gradually expands, a single data source and a single data source can no longer meet the support needs of demanding projects, such as multiple type libraries, one master and multiple slaves, and mixed modes, etc., thus extending the scope of multi-data source extension. The operation of multiple data sources is also common in daily development scenarios. Let's take a look at how we operate data in a multi-data source environment.
3.1 Configuration of multi-data source environment
First, add the environment dependency to enable multiple data sources in the configuration file.
<!--多数据源的依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
Configure data source: For the structure of multiple libraries, one master and multiple slaves, or a mixed mode, please refer to the official documentation. What is given here is one master and multiple slaves.
spring:
#配置数据源信息
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
master:
url: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&userSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
slave_1:
url: jdbc:mysql://localhost:3306/mybatis_plus_1?serverTimezone=GMT%2B8&characterEncoding=utf-8&userSSL=false
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
slave_2:
url: ENC(xxxxx) # 内置加密,使用请查看详细文档,文档需要付费!
username: ENC(xxxxx)
password: ENC(xxxxx)
driver-class-name: com.mysql.jdbc.Driver
#......省略
#以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2
3.2 Application of multiple data sources
Entity class
package com.crj.mybatisPlusDatasource.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("t_user")
public class User {
@TableId(value = "uid",type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
mapper interface
The mapper interface also needs to inherit the BaseMapper interface for CRUD database operations integrated in MyBatis-Plus and inherit the relevant CRUD code.
package com.crj.mybatisPlusDatasource.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.crj.mybatisPlusDatasource.pojo.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper extends BaseMapper<User> {
}
service interface
The service interface needs to inherit the IService interface of MyBatis-Plus to obtain class methods related to data operations.
package com.crj.mybatisPlusDatasource.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.crj.mybatisPlusDatasource.pojo.User;
import org.springframework.stereotype.Service;
public interface UserService extends IService<User> {
}
service interface implementation class
Note that @DS is used here to declare which data source the entity class interface uses!
package com.crj.mybatisPlusDatasource.service.impl;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crj.mybatisPlusDatasource.mapper.UserMapper;
import com.crj.mybatisPlusDatasource.pojo.User;
import com.crj.mybatisPlusDatasource.service.UserService;
import org.springframework.stereotype.Service;
@Service
@DS("master")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
Create a Product entity class using the same steps as creating the User entity class, and test whether multiple data sources are successfully opened in the test class.
The difference between Service layer and Mapper layer interfaces
A simple understanding is that the mapper layer interface inherits the BaseMapper interface to implement basic CRUD functions, while Service usually defines the business logic method of the application and provides a high-level abstraction of data. The Service layer interface implementation class implements business logic by calling basic CRUD operations in the BaseMapper interface.
Summarize
Finally, the phased learning of MyBatis-Plus is over, and Lizhi can return to the project learning hahahaha. Lizhi has been a little anxious recently, haha. I feel a little anxious. I still have to take the time to review my studies during this period. To lay a solid foundation, let’s start with software design patterns and design principles~~~
Today has become the past, but we still look forward to the future tomorrow! I am Xiaolizhi, and I will accompany you on the road of technological growth. Coding is not easy, so please raise your little paw and give me a thumbs up, hahaha~~~ Bixinxin♥~~~