【亲测有效】MybatisPlus中MetaObjectHandler自动填充字段失效
MybatisPlus中MetaObjectHandler自动填充字段失效问题
首先如下配置是最基础的, 本文解决的是失效问题, 如下基础配置不再赘述 !
MetaObjectHandler类
注意: MetaObjectHandler类不加@Component注解在config类中使用@Bean注解也可
//@Component
public class FillHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {this.strictInsertFill(metaObject, "createTime", Date.class, new Date());}@Overridepublic void updateFill(MetaObject metaObject) {this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());}
}
公共字段实体类(其他实体类继承即可)
@Data
public class BaseEntity {@TableId(type = IdType.AUTO)private Long id;//配置插入的时候自动填充create_time@TableField(value = "create_time", fill = FieldFill.INSERT)private Date createTime;//配置更新的时候自动填充create_time@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)private Date updateTime;
}
发现问题
MybatisPlus中MetaObjectHandler自动填充字段失效, 并且打断点到FillHandler中, 没有进入调试, 说明FillHandler压根没有注入到mybatis-plus中
解决问题
修改MybatisPlusConfig类中配置具体如下图所示
我的配置类代码如下, 按照自己项目的配置略微修改即可, 仅供参考
@Configuration
@MapperScan(value = {"com.lnsoft.sdhxgk.heartbeat.mapper", "com.lnsoft.sdhxgk.**.mapper"})
@RequiredArgsConstructor
public class MybatisPlusConfig {private final MybatisPlusProperties properties;@Bean@Primary@ConfigurationProperties("spring.datasource")public DataSource dataSource(){DataSource datasource = new DruidDataSource();return datasource;}@Bean@Primarypublic SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {factory.setMapperLocations(this.properties.resolveMapperLocations());}MybatisConfiguration configuration = this.properties.getConfiguration();if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {configuration = new MybatisConfiguration();}factory.setConfiguration(configuration);factory.setVfs(SpringBootVFS.class);GlobalConfig globalConfig = this.properties.getGlobalConfig();globalConfig.setMetaObjectHandler(new FillHandler());factory.setGlobalConfig(globalConfig);factory.setDataSource(dataSource);return factory.getObject();}@Beanpublic MetaObjectHandler metaObjectHandler() {return new FillHandler();}@Bean@Primarypublic DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource){return new DataSourceTransactionManager(dataSource);}@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();// 分页插件interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));// 乐观锁插件interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return interceptor;}
}
再次启动项目, 自动填充功能生效 !