0 pom依赖
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
1 文件组织结构
创建了两个数据库,主数据库wqx,辅数据库gis。
2 application.yml双数据库配置
spring:
profiles:
active: dev # 当选择的文件和当前存在相同的配置时会被覆盖掉
datasource:
druid:
gis: # 数据库1
username: postgres
password: postgres
url: jdbc:postgresql://localhost:5432/heny_gis?¤tSchema=public
driver-class-name: org.postgresql.Driver
type: com.alibaba.druid.pool.DruidDataSource #引入druid数据源
initialSize: 1 # 初始大小
minIdle: 5 # 最小
maxActive: 10 # 最大
maxWait: 60000 # 获取连接等待超时的时间:60秒
timeBetweenEvictionRunsMillis: 60000 # 间隔多久才进行一次检测,检测需要关闭的空闲连接,毫秒
minEvictableIdleTimeMillis: 300000 # 一个连接在池中最小生存的时间,毫秒
maxEvictableIdleTimeMillis: 900000 # 一个连接在池中最大生存的时间,毫秒
validationQuery: SELECT 1 # 检测连接是否有效
testWhileIdle: true # 取用连接时,通过与回收时间比较检测是否有效
testOnBorrow: false # 取用连接时,检测是否有效
testOnReturn: false # 归还连接时,检测是否有效
filters: slf4j,wall,stat # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
wqx: # 数据库2
username: postgres
password: postgres
url: jdbc:postgresql://localhost:5432/heny_wqx?¤tSchema=public
driver-class-name: org.postgresql.Driver
type: com.alibaba.druid.pool.DruidDataSource #引入druid数据源
initialSize: 1
minIdle: 5
maxActive: 10
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
maxEvictableIdleTimeMillis: 900000
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
filters: slf4j,wall,stat
3 双数据库配置类
以主数据库为例:
@Configuration
@MapperScan(basePackages = {"com.heny.wqx.mapper.wqx"}, sqlSessionFactoryRef = "wqxSqlSessionFactory")
public class HenyWqxConfig {
@Primary
@Bean(name = "wqxDataSource")
@ConfigurationProperties("spring.datasource.druid.wqx")
public DataSource dataSource() {
return DruidDataSourceBuilder.create().build();
}
@Primary
@Bean(name = "wqxTransactionManager")
public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("wqxDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Primary
@Bean(name = "wqxSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("wqxDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/wqx/*.xml"));
return factoryBean.getObject();
}
@Primary
@Bean(name = "wqxSqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("wqxSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}