多数据源配置与使用
一主一从
spring:
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
master:
url: jdbc:mysql://127.0.0.1:3306/rob_necessities?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone =Asia/Shanghai
username: root
password: 123456
slave_1:
url: jdbc:mysql://127.0.0.1:3306/rob_necessities?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone =Asia/Shanghai
username: root
password: 123456
补充 :这里面因为默认使用的是HikariCP数据源,目前也推荐使用这个,相比于druid有更高的性能,但是不能忽略下面的配置,否则服务会不断抛出异常,原因是数据库的连接时常和连接池的配置没有做好。
spring:
datasource:
dynamic:
hikari:
max-lifetime: 1800000
connection-timeout: 5000
idle-timeout: 3600000
max-pool-size: 12
min-idle: 4
connection-test-query: /**ping*/
分页配置
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan(\"com.wjbgn.*.mapper*\")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
逻辑删除配置
mybatis-plus:
global-config:
db-config:
logic-delete-field: isDelete # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
或者通过注解@TableLogic
@TableLogic
private Integer isDelete;
高级使用:
通用枚举配置
- 以返回的性别为例子
import com.baomidou.mybatisplus.annotation.IEnum;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* @description: 性别枚举
* @author:weirx
* @date:2022/1/17 16:26
* @version:3.0
*/
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum SexEnum implements IEnum<Integer> {
MAN(1, \"男\"),
WOMAN(2, \"女\");
private Integer code;
private String name;
SexEnum(Integer code, String name) {
this.code = code;
this.name = name;
}
@Override
public Integer getValue() {
return code;
}
public String getName() {
return name;
}
}
@JsonFormat 注解为了解决枚举类返回前端只展示构造器名称的问题。
- 实体类性别字段
@TableName(value = \"user\")
public class UserDO {
/**
* 主键
*/
@TableId(value = \"id\", type = IdType.AUTO)
private Long id;
/**
* 昵称
*/
@TableField(value = \"nickname\",condition = SqlCondition.EQUAL)
private String nickname;
/**
* 性别
*/
@TableField(value = \"sex\")
private SexEnum sex;
/**
* 版本
*/
@TableField(value = \"version\",update = \"%s+1\")
private Integer version;
/**
* 时间字段,自动添加
*/
@TableField(value = \"create_time\",fill = FieldFill.INSERT)
private LocalDateTime createTime;
}
- 配置文件扫描枚举
mybatis-plus:
# 支持统配符 * 或者 ; 分割
typeEnumsPackage: com.wjbgn.*.enums
- 定义配置文件
@Bean
public MybatisPlusPropertiesCustomizer mybatisPlusPropertiesCustomizer() {
return properties -> {
GlobalConfig globalConfig = properties.getGlobalConfig();
globalConfig.setBanner(false);
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setDefaultEnumTypeHandler(MybatisEnumTypeHandler.class);
properties.setConfiguration(configuration);
};
}
@Bean
public MybatisPlusPropertiesCustomizer mybatisPlusPropertiesCustomizer() {
// 序列化枚举值为数据库存储值
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.WriteEnumUsingToString);
return properties -> {
GlobalConfig globalConfig = properties.getGlobalConfig();
globalConfig.setBanner(false);
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setDefaultEnumTypeHandler(MybatisEnumTypeHandler.class);
properties.setConfiguration(configuration);
};
}
@TableFeild FieldFill 属性
public enum FieldFill {
/**
* 默认不处理
*/
DEFAULT,
/**
* 插入填充字段
*/
INSERT,
/**
* 更新填充字段
*/
UPDATE,
/**
* 插入和更新填充字段
*/
INSERT_UPDATE
}
- 这个直接是不能使用的,需要通过实现 mybatis-plus 提供的接口,增加如下配置:
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* description: 启动自动填充功能
* @return:
* @author: weirx
* @time: 2022/1/17 17:00
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
// 起始版本 3.3.0(推荐使用)
this.strictInsertFill(metaObject, \"createTime\", LocalDateTime.class, LocalDateTime.now());
}
@Override
public void updateFill(MetaObject metaObject) {
// 起始版本 3.3.0(推荐)
this.strictUpdateFill(metaObject, \"updateTime\", LocalDateTime.class, LocalDateTime.now());
}
}
多类型兼容配置
private static final String CREATE_TIME = "createTime";
private static final String UPDATE_TIME = "updateTime";
@Override
public void insertFill(MetaObject metaObject) {
extracted(metaObject, CREATE_TIME);
}
@Override
public void updateFill(MetaObject metaObject) {
extracted(metaObject, UPDATE_TIME);
}
private static void extracted(MetaObject metaObject, String fieldName) {
try {
Object now = null;
if (metaObject.hasGetter("et")) {
Object et = metaObject.getValue("et");
if (et != null) {
MetaObject etMeta = SystemMetaObject.forObject(et);
if (etMeta.hasSetter(fieldName)) {
Class<?> createTime = etMeta.getGetterType(fieldName);
String name = createTime.getName();
switch (name) {
case "java.util.Date":
now = new Date();
break;
case "java.time.LocalDateTime":
now = LocalDateTime.now();
break;
case "java.time.LocalDate":
now = LocalDate.now();
break;
case "java.lang.String":
now = DateTimeString.DATE_TIME.toString(LocalDateTime.now());
break;
}
etMeta.setValue(fieldName, now);
}
}
}
} catch (Exception e) {
log.info("Fill:{}", e.getMessage());
}
}
- 使用
/**
* 时间字段,自动添加
*/
@TableField(value = \"create_time\",fill = FieldFill.INSERT)
private LocalDateTime createTime;
多数据源
- 多主多从
spring:
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
master_1:
master_2:
slave_1:
slave_2:
slave_3:
- 多种数据库
spring:
datasource:
dynamic:
primary: mysql #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
mysql:
oracle:
postgresql:
h2:
sqlserver:
- 混合配置
spring:
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
master_1:
slave_1:
slave_2:
oracle_1:
oracle_2:
- 使用 @DS 注解
可以注解在方法上或类上,同时存在就近原则 【方法上注解】 优先于 【类上注解】 :
@DS(\"slave_1\")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements IUserService {
@DS(\"salve_1\")
@Override
public List<UserDO> getList() {
return this.getList();
}
@DS(\"master\")
@Override
public int saveUser(UserDO userDO) {
boolean save = this.save(userDO);
if (save){
return 1;
}else{
return 0;
}
}
}