我们熟知的数据库连接池有出c3p0,DBCP,Druid,Hikari.。
其中c3p0已经很久没有更新了。DBCP更新速度很慢。Druid和Hikari是现在的主流连接池。
现在用阿里的Druid进行集成
添加依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.22</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.4.4</version>
</dependency>
配置文件问更改数据库连接池为druid(springboot2.0默认的是hikari)
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
配置mybatis的mapper的xml文件过滤位置:
mybatis.mapper-locations=classpath: mapper/com/example/*/*.xml
mybatis.type-aliases-package=这个配置要扫描的model的包名,多个的话用分号(;)隔开
配置多数据源:
spring.datasource.druid.one.name=DBconfig1
spring.datasource.druid.one.url=jdbc:mysql://127.0.0.1:3306/slaveone?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.druid.one.username=root
spring.datasource.druid.one.password=456
spring.datasource.druid.one.driver-class-name=com.mysql.jdbc.Driver
#--------------------------------
spring.datasource.druid.two.name=DBconfig2
spring.datasource.druid.two.url=jdbc:mysql://127.0.0.1:3306/slavetwo?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.druid.two.username=root
spring.datasource.druid.two.password=456
spring.datasource.druid.two.driver-class-name=com.mysql.jdbc.Driver
编写配置类:
1.在类上加上注解@Configuration
2.加上注解@MapperScan
3.实现类DataSource, sqlSessionFactory,sqlSessionTemplate,dataSourceTransactionManager.
eg:
@Configuration
@MapperScan(basePackages = {"com.example.manysource.dao.mapper.one"},sqlSessionTemplateRef="sqlSessionTemplateOne")
public class DataOne {
@Value("${mybatis.mapper-locations}")
private Stringmapper_location;
@Bean(name ="dataSourceone")
@ConfigurationProperties(prefix ="spring.datasource.druid.one")
public DataSource dataSourceone() {
return DruidDataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory sqlSessionFactoryone(@Qualifier("dataSourceone") DataSource dataSource)throws Exception {
SqlSessionFactoryBean bean =new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//如果重写了 SqlSessionFactory 需要在初始化的时候手动将 mapper 地址 set到 factory 中,否则会报错:
//org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper_location));
return bean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplateone(@Qualifier("sqlSessionFactoryone") SqlSessionFactory sqlSessionFactory) {
SqlSessionTemplate template =new SqlSessionTemplate(sqlSessionFactory);
return template;
}
/**
* 为选中的数据源 dataSourceone 添加事务管理
* @param dataSource
* @return
*/
@Bean
public DataSourceTransactionManager transactionManagerone(@Qualifier("dataSourceone") DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}