1、修改application.properties
新建 Mapper、实体类 相应的文件夹,将不同数据源的文件保存到对应的文件夹下
# test1 数据库的配置
test1.spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
test1.spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/database1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
test1.spring.datasource.username=username
test1.spring.datasource.password=password
# test2 数据库的配置
test2.spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
test2.spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/database2?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
test2.spring.datasource.username=username
test2.spring.datasource.password=password
# 配置 mybatis 配置 mapper.xml 文件路径mybatis.mapper-locations=classpath:/mapper//
扫描 Mapper 接口并容器管理
@MapperScan(basePackages = Test1DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "test1SqlSessionFactory")
@Configuration
public class Test1DataSourceConfig {
// 精确到 test1 目录,以便跟其他数据源隔离
static final String PACKAGE = "com.xxx.dao.test1";
static final String MAPPER_LOCATION = "classpath:mapper/test1
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = Test2DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "test2SqlSessionFactory")
@Configuration
public class Test2DataSourceConfig {
// 精确到 test2 目录,以便跟其他数据源隔离
static final String PACKAGE = "com.xxx.dao.test2";
static final String MAPPER_LOCATION = "classpath:mapper/test2/*.xml";
@Value("${test2.spring.datasource.jdbc-url}")
private String url;
@Value("${test2.spring.datasource.username}")
private String user;
@Value("${test2.spring.datasource.password}")
private String password;
@Value("${test2.spring.datasource.driver-class-name}")
private String driverClass;
@Bean(name = "test2DataSource")
public DataSource test2DataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "test2TransactionManager")
public DataSourceTransactionManager test2TransactionManager() {
return new DataSourceTransactionManager(test2DataSource());
}
@Bean(name = "test2SqlSessionFactory")
public SqlSessionFactory test2SqlSessionFactory(@Qualifier("test2DataSource") DataSource test2DataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(test2DataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(Test2DataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject(); }
}
搞定,轻轻松松~
注:
- mapper文件夹下新建的文件夹需要有 *.xml 文件( 即:classpath:/mapper/xxx/*.xml下要存在文件 ),不然可能检测不到
- 需要继续添加数据源就再加一个其他数据源
以上就是方便快捷实现springboot 后端配置多个数据源、Mysql数据库的详细内容,更多关于springboot 后端配置多个数据源、Mysql数据库的资料请关注编程网其它相关文章!希望大家以后多多支持编程网!