Mybatisplus自动填充功能失效

通过SpringBoot框架集成 mybatis-plus
首先导入需要的依赖

<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.3.2</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.3.2</version></dependency>

在appication.yml添加相关配置

mybatis-plusconfiguration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl//打印sql语句mapper-locations: com/example/mapper/xml/*.xml // 配置mapper的扫描,找到所有的mapper.xml映射文件

创建实体类对象

@Data@AllArgsConstructor@NoArgsConstructorpublic class OrderMaster implements Serializable {@TableId(type = IdType.ASSIGN_UUID)//自动生成private String orderId;private String Name;private String Phone;private String Address;/** * 创建时间 */@TableField(fill = FieldFill.INSERT)private LocalDateTime createTime;/** * 修改时间 */@TableField(fill = FieldFill.INSERT_UPDATE)private LocalDateTime updateTime;}

按照官方文档进行配置
要记得添加@Component注解

@Component//自动填充配置public class FillHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {log.info("开始填充时间");this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());this.setFieldValByName("updateTime", LocalDateTime.now(),metaObject);}@Overridepublic void updateFill(MetaObject metaObject) {this.setFieldValByName("updateTime", LocalDateTime.now(),metaObject);}}

正常来说到了这一步,一般情况下就好了
常见的错误有这几种

  • 日期类不一致导致 创建日期、更新日期 为 null
  • @Component 没有被扫到,可以看下启动类的位置,启动类扫描的包是在其所在包以下的包
  • 还有就是填充的字段属性不一致,比如Date和LocalDateTime
  • 检查MetaObjectHandler实现类是否使用@Component
  • 实体类字段使用注解 @TableField(fill = FieldFill.INSERT)

可惜我的问题不是以上几种,于是我打了断点,发现根本没有执行到 MetaObjectHandler的实现类=>FillHandler
于是我输出了所有的bean,发现MetaObjectHandler并没有注入进去。
这里的原因在于mybatis有自己默认的配置文件,所以我们自定义的没有生效,自定义Bean sqlSessionFactory 影响到了 globalConfig ,导致配置失效。
添加这样一个配置类即可

import com.baomidou.mybatisplus.core.config.GlobalConfig;import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;import com.example.handler.FillHandler;import org.apache.ibatis.session.SqlSessionFactory;import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class sqlSessionFactory {@Beanpublic SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();//获取mybatis-plus全局配置GlobalConfig globalConfig = GlobalConfigUtils.defaults();//mybatis-plus全局配置设置元数据对象处理器为自己实现的那个globalConfig.setMetaObjectHandler(new FillHandler());mybatisSqlSessionFactoryBean.setDataSource(dataSource);//mybatisSqlSessionFactoryBean关联设置全局配置mybatisSqlSessionFactoryBean.setGlobalConfig(globalConfig);return mybatisSqlSessionFactoryBean.getObject();}}

到这里就终于好了,这个问题困扰了我一整天,终于解决了!