根据一个项目需求对数据进行转换,从一个数据库中读取数据,经过转换处理后转到另外一个数据库中。故考虑用到多数据源配置
github地址
application.properties
server.port=8082
# editor数据源
spring.datasource.editor.name=test
spring.datasource.editor.driverClassName = org.postgresql.Driver
spring.datasource.editor.jdbcUrl=jdbc:postgresql://127.0.0.1:5432/test
spring.datasource.editor.username=postgres
spring.datasource.editor.password=xxx
# xd数据源
spring.datasource.xd.name=test1
spring.datasource.xd.jdbcUrl=jdbc:postgresql://127.0.0.1:5432/test1
spring.datasource.xd.driverClassName = org.postgresql.Driver
spring.datasource.xd.username=postgres
spring.datasource.xd.password=xxx
mybatis.mapper-locations=classpath:com.threestone.dao/mapping/**/*.xml
mybatis.type-aliases-package=com.threestone.model
mybatis.type-handlers-package=com.threestone.common.mybatisTypeHandler
禁止spring自动加载数据库配置,在启动类上加上如下代码
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,DataSourceTransactionManagerAutoConfiguration.class, MybatisAutoConfiguration.class})
我们工程的结构如下图
禁止后需要加上自定义的数据库配置
主数据源配置类
EditorDataSourceConfig.java
@Configuration
@MapperScan(basePackages = "com.threestone.dao.editor",sqlSessionFactoryRef = "editorSqlSessionFactory")
public class EditorDataSourceConfig {
@Primary
@Bean(name = "editorDataSource")
@ConfigurationProperties("spring.datasource.editor")
public DataSource masterDataSource(){
return DataSourceBuilder.create().build();
}
@Bean(name = "editorSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("editorDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:**/dao/mapping/editor/*.xml"));
return sessionFactoryBean.getObject();
}
}
次数据源配置类
XDDataSourceConfig.java
@Configuration
@MapperScan(basePackages = "com.threestone.dao.xd",sqlSessionFactoryRef = "xdSqlSessionFactory")
public class XDDataSourceConfig {
@Primary
@Bean(name = "xdDataSource")
@ConfigurationProperties("spring.datasource.xd")
public DataSource masterDataSource(){
return DataSourceBuilder.create().build();
}
@Bean(name = "xdSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("xdDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:**/dao/mapping/xd/*.xml"));
return sessionFactoryBean.getObject();
}
}
根据我们自己定义的xml地址和dao文件地址将相应文件放到相应目录中,参照上图中的项目结构。
水平有限,如有不正确的地方欢迎指正
来源:CSDN
作者:三石兄_2010
链接:https://blog.csdn.net/qq_40224400/article/details/104000492