Mybatis Plus多源数据库和自动更新updateTime问题

多源数据库配置

1、依赖配置

    implementation 'com.baomidou:mybatis-plus-boot-starter:3.5.2'
    implementation 'com.baomidou:dynamic-datasource-spring-boot-starter:3.5.2'

2、配置文件

spring:
  datasource:
    dynamic:
      primary: master #设置默认的数据源或者数据源组,默认值即为master
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        master:
          url: jdbc:mysql://localhost:3306/db1?autoReconnect=true&failOverReadOnly=false&characterEncoding=utf8&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&useSSL=false
          username: test
          password: test
          driver-class-name: com.mysql.cj.jdbc.Driver
        db2:
          url: jdbc:mysql://localhost:3306/db2?useSSL=false&autoReconnect=true&statementInterceptors=brave.mysql.TracingStatementInterceptor&characterEncoding=utf8&serverTimezone=Asia/Shanghai
          username: test
          password: test

3、数据库切换

@DS("master")
@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {
}

4、debug日志

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

自动更新数据库的updateTime字段

1、实体类字段

@Data
public class UserEntity {

    @TableId(type = AUTO)
    private Integer id;

    @TableField("user_id")
    private String userId;

    /**
     * 创建时间
     */
    @JsonFormat(shape = JsonFormat.Shape.NUMBER)
    @TableField(value = "create_time", fill = FieldFill.INSERT)
    private Date createTime;

    /**
     * 更新时间
     */
    @JsonFormat(shape = JsonFormat.Shape.NUMBER)
    @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}

2、配置

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

@Configuration
public class MybatisConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                this.setFieldValByName("createTime", new Date(), metaObject);
                this.setFieldValByName("updateTime", new Date(), metaObject);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                this.setFieldValByName("updateTime", new Date(), metaObject);
            }
        };
    }
}

3、使用方式

@DS("master")
@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {
}
public interface UserRepository extends IService<UserEntity> {
     void update(UserEntity entity);
}
@Slf4j
@Repository
@RequiredArgsConstructor
public class UserRepositoryImpl extends ServiceImpl<UserMapper, UserEntity> implements UserRepository {
    @Override
    public void update(UserEntity entity) {
        this.update(entity, new LambdaUpdateWrapper<UserEntity>()
                    .eq(UserEntity::getUserId, userId));
    }
}

注意,以下方式是无法自动更新时间的

this.update(new LambdaUpdateWrapper<UserEntity>()
                    .eq(UserEntity::getUserId, userId)
                    .set(UserEntity::getNickName, "nickName"));
posted @ 2024-09-27 09:56  风小雅  阅读(28)  评论(0编辑  收藏  举报