1、在配置文件中加入多数据源信息(不同数据库类型,pom文件中要引入相对应的数据库驱动)
datasource: local: jdbc-url: jdbc:postgresql://ip:port/cpic?currentSchema=********* username: ********* password: ********* gpt: driver-class-name: oracle.jdbc.OracleDriver jdbc-url: jdbc:oracle:thin:@ip:port:orcl username: ********* password: ********* ott: driver-class-name: oracle.jdbc.OracleDriver jdbc-url: jdbc:oracle:thin:@ip:port:orcl username: ********* password: ********* mf: driver-class-name: oracle.jdbc.OracleDriver jdbc-url: jdbc:oracle:thin:@ip:port:orcl username: ********* password: *********
2、添加配置类(@MapperScan),如上图需要建四个配置类,这里拿一个举例
@Configuration @MapperScan(basePackages = "com.clamc.collection.mapper.mf", sqlSessionFactoryRef = "mfSqlSessionFactory", sqlSessionTemplateRef = "mfSqlSessionTemplate") public class MfDataSourceConfig { @Bean("mfDataSource") @ConfigurationProperties(prefix = "spring.datasource.mf") //读取application.yml中的配置参数映射成为一个对象 public DataSource getmfDataSource(){ return DataSourceBuilder.create().build(); } @Bean("mfSqlSessionFactory") public SqlSessionFactory mfSqlSessionFactory(@Qualifier("mfDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); // mapper的xml形式文件位置必须要配置,不然将报错:no statement (这种错误也可能是mapper的xml中,namespace与项目的路径不一致导致) bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/mf/*.xml")); return bean.getObject(); } @Bean("mfSqlSessionTemplate") public SqlSessionTemplate mfSqlSessionTemplate(@Qualifier("mfSqlSessionFactory") SqlSessionFactory sqlSessionFactory){ return new SqlSessionTemplate(sqlSessionFactory); } }
指定要读的mapper路径即可,项目路径如下: