@Configuration
@MapperScan(value = {"com.***.***.dal.mysql.mapper"}, sqlSessionFactoryRef = "mysqlSqlSessionFactory")
public class MysqlDataConfig {
/```省略@value注入的datasource属性```/
@Bean("dataSource") //新建bean实例
public DataSource dataSource() {
HikariDataSource hikariDataSource = new HikariDataSource();
hikariDataSource.setDriverClassName(driveClassName);
hikariDataSource.setJdbcUrl(jdbcUrl);
hikariDataSource.setUsername(userName);
hikariDataSource.setPassword(password);
hikariDataSource.setMaximumPoolSize(maxPoolSize);
hikariDataSource.setMinimumIdle(minIdle);
hikariDataSource.setConnectionTimeout(connectionTimeout);
hikariDataSource.setIdleTimeout(idleTimeout);
hikariDataSource.setMaxLifetime(maxLifetime);
hikariDataSource.setConnectionTestQuery(connectionTestQuery);
hikariDataSource.setConnectionInitSql(connectionInitSql);
return hikariDataSource;
}
@Bean(name = "templateReport")
public JdbcTemplate templateXbRisk() {
return new JdbcTemplate(dataSource());
}
@Bean("mysqlSqlSessionFactory")
@Primary
public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource)
throws Exception {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/mysql/*.xml"));
bean.setDataSource(dataSource);
MybatisConfiguration config = new MybatisConfiguration();
// 开启驼峰命名映射
config.setMapUnderscoreToCamelCase(true);
bean.setConfiguration(config);
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setMetaObjectHandler(new MysqlMetaObjectHandler());
bean.setGlobalConfig(globalConfig);
return bean.getObject();
}
}
public class MysqlMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
Object createdBy = this.getFieldValByName("createdBy", metaObject);
String username = Objects.nonNull(createdBy) ? String.valueOf(createdBy) : "SYSTEM";
this.setFieldValByName("createdBy", username, metaObject);
this.setFieldValByName("createdAt", new Date(), metaObject);
this.setFieldValByName("updatedBy", username, metaObject);
this.setFieldValByName("updatedAt", new Date(), metaObject);
//有值,则写入
if (metaObject.hasGetter("deleteFlag")) {
this.setFieldValByName("deleteFlag", false, metaObject);
}
}
@Override
public void updateFill(MetaObject metaObject) {
Object updatedBy = this.getFieldValByName("updatedBy", metaObject);
String username = Objects.nonNull(updatedBy) ? String.valueOf(updatedBy) : "SYSTEM";
this.setFieldValByName("updatedBy", username, metaObject);
this.setFieldValByName("updatedAt", new Date(), metaObject);
}
}