对于大型项目,多数据源是非常有必要的。
1、在Application.yml中配置多数据源
spring: datasource: ###用户数据库 user: jdbc-url: jdbc:mysql://localhost:3306/user username: root password: root driver-class-name: com.mysql.jdbc.Driver ###新闻数据库 news: jdbc-url: jdbc:mysql://localhost:3306/news username: root password: root driver-class-name: com.mysql.jdbc.Driver
2、创建数据源配置
package com.example.demo.mapper; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = "com.example.demo.user", sqlSessionTemplateRef = "userSqlSessionTemplate") //注1:此处user对应数据源指向的package的位置。 //即com.example.demo.user下面的数据调用将使用对应设置的数据源 public class MemberDataSourceConfig { /** * 创建数据源 * @return */ @Bean("userDataSource") @ConfigurationProperties(prefix = "spring.datasource.user") //注2:此处spring.datasource.user对应Application.yml的数据库对应配置 public DataSource userDataSource(){ return DataSourceBuilder.create().build(); } /** * 创建SqlSessionFactory * @param dataSource * @return * @throws Exception */ @Bean(name = "userSqlSessionFactory") public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(userDataSource()); return sqlSessionFactoryBean.getObject(); } /** * 创建管理器 * @param dataSource * @return */ @Bean(name = "userTransactionManager") public DataSourceTransactionManager userTranscationManager(@Qualifier("userDataSource") DataSource dataSource){ return new DataSourceTransactionManager(dataSource); } /** * 创建模板 * @param sqlSessionFactory * @return * @throws Exception */ @Bean(name = "userSqlSessionTemplate") public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userSqlSessionFactory")SqlSessionFactory sqlSessionFactory) throws Exception{ return new SqlSessionTemplate(sqlSessionFactory); } }
经过以上配置后,对应的路径com.example.demo.user下面的数据即对应关联对应的数据源了。