springboot里配置多数据源
写2个数据源配置类,分别指到不同的DAO操作数据库文件
mysql的
@Configuration @MapperScan(basePackages = {"com.heeexy.example.dao.mysql"},sqlSessionFactoryRef = "mysqlsqlSessionFactory") public class MyBatisMysqlAConfig { @Autowired @Qualifier("mysqlDataSource") private DataSource dataSource; @Bean public SqlSessionFactory mysqlsqlSessionFactory() throws Exception{ SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resource=resolver.getResources("classpath:mapper/mysql/*.xml");//对应的mybatis的文件目录 sqlSessionFactoryBean.setMapperLocations(resource); return sqlSessionFactoryBean.getObject(); } @Bean public SqlSessionTemplate mysqlsqlSession() throws Exception{ SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(mysqlsqlSessionFactory()); return sqlSessionTemplate; } }
sqlService的类
@Configuration @MapperScan(basePackages = {"com.heeexy.example.dao.paiban"},sqlSessionFactoryRef = "paibansqlSessionFactory") public class MyBatisPaibanAConfig { @Autowired @Qualifier("paibanDataSource") private DataSource dataSource; @Bean public SqlSessionFactory paibansqlSessionFactory() throws Exception{ SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resource=resolver.getResources("classpath:mapper/paiban/*.xml");//对应的mybatis的文件目录 sqlSessionFactoryBean.setMapperLocations(resource); return sqlSessionFactoryBean.getObject(); } @Bean public SqlSessionTemplate paibansqlSession() throws Exception{ SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(paibansqlSessionFactory()); return sqlSessionTemplate; } }
增加一个DataSourceConfig类
@Configuration public class DataSourceConfig { @Primary @Bean(name="mysqlDataSource") @ConfigurationProperties(prefix = "spring.datasource.mysql") public DataSource readDataSource(){ return DataSourceBuilder.create().build(); } @Bean(name="paibanDataSource") @ConfigurationProperties(prefix = "spring.datasource.sqlservice") public DataSource paibanDataSource(){ return DataSourceBuilder.create().build(); }
}
配置文件配置不同数据源的配置
在操作DAO类的时候,会根据配置获取对应的dataSource,
这样就可以操作不同的数据库了