mybaties plus 高级用法

本文介绍了一种在Spring Boot应用中配置多数据源的方法,并详细讲解了如何利用MyBatis Plus进行分页配置、逻辑删除及实体枚举配置等高级用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

多数据源配置与使用

一主一从

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;
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值