在本地进行开发的时候,需要打印读库的sql,但是常规的配置是无法打印的,需要在读库的配置中进行设置。
第一种方案
通过设置logImpl
@Configuration
@MapperScan(basePackages = "com.xxx.readonly.dao", sqlSessionFactoryRef = "readonlySqlSessionFactory")
public class ReadDbConfig {
@Bean(name = "readDataSource")
@ConfigurationProperties(prefix = "spring.datasource.readonly")
public DataSource createDataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "readonlySqlSessionFactory")
public SqlSessionFactory createSqlSessionFactory(@Qualifier("readDataSource") DataSource masterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(masterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:readmapper/*.xml"));
// 打印sql
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
sessionFactory.setConfiguration(configuration);
return sessionFactory.getObject();
}
@Bean(name = "readTransactionManager")
public DataSourceTransactionManager createTransactionManager(@Qualifier("readDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
第二种方案
添加 MybatisProperties
@Configuration
@MapperScan(basePackages = "com.xxx.readonly.dao", sqlSessionFactoryRef = "readonlySqlSessionFactory")
public class ReadDbConfig {
@Bean(name = "readDataSource")
@ConfigurationProperties(prefix = "spring.datasource.readonly")
public DataSource createDataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "readonlySqlSessionFactory")
public SqlSessionFactory createSqlSessionFactory(@Qualifier("readDataSource") DataSource masterDataSource, MybatisProperties mybatisPropertie)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(masterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:readmapper/*.xml"));
// org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
// configuration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
// sessionFactory.setConfiguration(configuration);
sessionFactory.setConfiguration(mybatisPropertie.getConfiguration());
return sessionFactory.getObject();
}
@Bean(name = "readTransactionManager")
public DataSourceTransactionManager createTransactionManager(@Qualifier("readDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}