项目中需要用到Mybatis的插件,配置插件的时候需要自定义SqlSessionFactory
网上的信息不太准确,本文记录订正并共享大家。
Mybatis-plus 和Mybatis 是兼容的。
所以网上的配置 mybatis 的SqlSessionFactory 的方法基本上可行,但是对于mybatis-plus 的一些特性会丢失 例如
@TableField(fill = FieldFill.INSERT) 注解
正确的配置方式:
@Component
public class DateAutoFillHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("modifyTime", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("modifyTime", new Date(), metaObject);
}
}
@Autowired
MybatisPlusInterceptor mybatisPlusInterceptor;
@Autowired
SqlPrintInterceptor sqlPrintInterceptor;
@Bean(name = "globalConfig")
public GlobalConfig globalConfig(@Qualifier("dateAutoFillHandler") DateAutoFillHandler dateAutoFillHandler) {
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setMetaObjectHandler(dateAutoFillHandler);
return globalConfig;
}
@Bean(name = "sqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("db1") DataSource ds, @Qualifier("globalConfig") GlobalConfig globalConfig) throws Exception {
MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
factoryBean.setPlugins(new Interceptor[]{mybatisPlusInterceptor, sqlPrintInterceptor});
factoryBean.setDataSource(ds);
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
configuration.setJdbcTypeForNull(JdbcType.NULL);
factoryBean.setConfiguration(configuration);
factoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
factoryBean.setGlobalConfig(globalConfig);
return factoryBean.getObject();
}
这样 mybatis-plus 自定义sqlSessionFactory 就配置好了
参考资料:https://www.fancv.com/article/1646836381
|