需求
springboot+mybatis+mysql整合工程,结合tk-mybatis技术,实现多个数据源配置。
实现方式一
- 第一步:application.yml配置文件
spring:
# 多数据源
permission:
datasource:
url: jdbc:mysql://127.0.0.1:3306/permission?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
account:
datasource:
url: jdbc:mysql://127.0.0.1:3306/account?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
- 第二步:取消springboot自动初始化数据源
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
JdbcTemplateAutoConfiguration.class})
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
- 第三步:数据源配置实体类
第一数据源:
package com.dashboard.common.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;
import javax.annotation.Resource;
import javax.sql.DataSource;
/**
* @author konglinghui
* @description account数据源配置
* @date 2020/4/19 10:09
**/
@Configuration
@MapperScan(basePackages = {"com.dashboard.mapper.account"}, sqlSessionTemplateRef = "accountSqlSessionTemplate")
public class AccountDataSourceConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(AccountDataSourceConfig.class);
/**
* 数据源配置对象
* Primary 表示默认的对象,Autowire可注入,不是默认的得明确名称注入
*
* @return
*/
@Bean
// @Primary
@ConfigurationProperties("spring.account.datasource")
public DataSourceProperties accountDataSourceProperties() {
return new DataSourceProperties();
}
/**
* 数据源对象
*
* @return
*/
@Bean
public DataSource accountDataSource() {
DataSourceProperties dataSourceProperties = this.accountDataSourceProperties();
return dataSourceProperties.initializeDataSourceBuilder().build();
}
/**
* 配置事务
*
* @param accountDataSource
* @return
*/
@Bean
@Resource
public PlatformTransactionManager accountTransactionManager(DataSource accountDataSource) {
return new DataSourceTransactionManager(accountDataSource);
}
/**
* 配置Mapper路径
*
* @param dataSource
* @return
*/
@Bean
public SqlSessionFactory accountSqlSessionFactory(@Qualifier("accountDataSource") DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
// 添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
sqlSessionFactoryBean.setTypeAliasesPackage("com.dashboard.entity");
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/**Mapper.xml"));
return sqlSessionFactoryBean.getObject();
} catch (Exception e) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("配置Mapper路径发生异常:{}", e.getMessage());
}
e.printStackTrace();
}
return null;
}
/**
* 配置SqlSessionTemplate
*
* @param sqlSessionFactory
* @return
*/
@Bean
public SqlSessionTemplate accountSqlSessionTemplate(@Qualifier("accountSqlSessionFactory")
SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
第二数据源:
package com.dashboard.common.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;
import javax.annotation.Resource;
import javax.sql.DataSource;
/**
* @author konglinghui
* @description permission数据源配置
* @date 2020/4/19 10:09
**/
@Configuration
@MapperScan(
basePackages = {"com.dashboard.mapper.permission", "com.dashboard.mapper.system"},
sqlSessionTemplateRef = "permissionSqlSessionTemplate")
public class PermissionDataSourceConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(PermissionDataSourceConfig.class);
/**
* 数据源配置对象
* Primary 表示默认的对象,Autowire可注入,不是默认的得明确名称注入
*
* @return
*/
@Bean
// @Primary
@ConfigurationProperties("spring.permission.datasource")
public DataSourceProperties permissionDataSourceProperties() {
return new DataSourceProperties();
}
/**
* 数据源对象
*
* @return
*/
@Bean
public DataSource permissionDataSource() {
DataSourceProperties dataSourceProperties = this.permissionDataSourceProperties();
return dataSourceProperties.initializeDataSourceBuilder().build();
}
/**
* 配置事务
*
* @param permissionDataSource
* @return
*/
@Bean
@Resource
public PlatformTransactionManager permissionTransactionManager(DataSource permissionDataSource) {
return new DataSourceTransactionManager(permissionDataSource);
}
/**
* 配置Mapper路径
*
* @param dataSource
* @return
*/
@Bean
public SqlSessionFactory permissionSqlSessionFactory(@Qualifier("permissionDataSource") DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
// 添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
sqlSessionFactoryBean.setTypeAliasesPackage("com.dashboard.entity");
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/**Mapper.xml"));
return sqlSessionFactoryBean.getObject();
} catch (Exception e) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("配置Mapper路径发生异常:{}", e.getMessage());
}
e.printStackTrace();
}
return null;
}
/**
* 配置SqlSessionTemplate
*
* @param sqlSessionFactory
* @return
*/
@Bean
public SqlSessionTemplate permissionSqlSessionTemplate(@Qualifier("permissionSqlSessionFactory")
SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
@Primary
:该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让autowire注解报错,官网要求当多个数据源时,必须指定一个datasource,另一个datasource则不用添加。(这里不需要,因为这里没有主从数据库,所有的数据源都是一样的)。@Qualifier
:根据名称进行注入,通常是在具有相同的多个类型的实例的一个注入(例如有多个DataSource类型的实例)。@MapperScan(basePackages = {"com.example.fjk.demo.dao.foo"}, sqlSessionTemplateRef = "fooSqlSessionTemplate")
:basePackages为Dao所在的包,sqlSessionTemplateRef要引用的实例。
常见问题
Failed to determine a suitable driver class
问题
异常信息如下:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-05-06 21:27:18.275 ERROR 10968 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
Process finished with exit code 1
问题根源:
1. ConfigurationProperties
注解属性值配置错误;
2. 取消springboot自动初始化数据源
操作失败。