SpringBoot和Mybatis配置多数据源连接多个数据库
目前业界操作数据库的框架一般是 Mybatis,但在很多业务场景下,我们需要在一个工程里配置多个数据源来实现业务逻辑。在SpringBoot中也可以实现多数据源并配合Mybatis框架编写xml文件来执行SQL。在SpringBoot中,配置多数据源的方式十分便捷,
下面开始上代码:
在pom.xml文件中需要添加一些依赖
org.mybatis.spring.bootmybatis-spring-boot-starter1.2.0mysqlmysql-connector-java5.1.39com.alibabadruid1.0.18
application.properties 配置两个数据源配置
# master 数据源配置master.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8master.datasource.username=rootmaster.datasource.password=321master.datasource.driverClassName=com.mysql.jdbc.Driver# second 数据源配置second.datasource.url=jdbc:mysql://localhost:3306/springbootdb_second?useUnicode=true&characterEncoding=utf8second.datasource.username=rootsecond.datasource.password=321second.datasource.driverClassName=com.mysql.jdbc.Driver
数据源配置
多数据源配置的时候注意,必须要有一个主数据源,即 MasterDataSourceConfig 配置
@Primary 标志这个 Bean 如果在多个同类 Bean 候选时,该 Bean 优先被考虑。「多数据源配置的时候注意,必须要有一个主数据源,用 @Primary 标志该 Bean
@MapperScan 扫描 Mapper 接口并容器管理,包路径精确到 master,为了和下面 cluster 数据源做到精确区分
@Value 获取全局配置文件 application.properties 的 kv 配置,并自动装配sqlSessionFactoryRef 表示定义了 key ,表示一个唯一 SqlSessionFactory 实例
MasterDataSourceConfig的代码:
@Configuration// 扫描 Mapper 接口并容器管理@MapperScan(basePackages = MasterDataSourceConfig.PACKAGE, sqlSessionFactoryRef ="masterSqlSessionFactory")publicclassMasterDataSourceConfig{// 精确到 master 目录,以便跟其他数据源隔离staticfinalString PACKAGE ="org.spring.springboot.dao.master"; staticfinalString MAPPER_LOCATION ="classpath:mapper/master/*.xml";@Value("${master.datasource.url}")privateString url;@Value("${master.datasource.username}")privateString user;@Value("${master.datasource.password}")privateString password;@Value("${master.datasource.driverClassName}")privateString driverClass;@Bean(name ="masterDataSource")@PrimarypublicDataSource masterDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driverClass); dataSource.setUrl(url); dataSource.setUsername(user); dataSource.setPassword(password);returndataSource; }@Bean(name ="masterTransactionManager")@PrimarypublicDataSourceTransactionManager masterTransactionManager() {returnnew DataSourceTransactionManager(masterDataSource()); }@Bean(name ="masterSqlSessionFactory")@PrimarypublicSqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource")DataSource masterDataSource) throws Exception {finalSqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(masterDataSource); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(MasterDataSourceConfig.MAPPER_LOCATION));returnsessionFactory.getObject(); }}
第二个数据源SecondDataSourceConfig的配置如下:
@Configuration// 扫描 Mapper 接口并容器管理@MapperScan(basePackages = SecondDataSourceConfig.PACKAGE, sqlSessionFactoryRef ="secondSqlSessionFactory")publicclassSecondDataSourceConfig{// 精确到 cluster 目录,以便跟其他数据源隔离staticfinalString PACKAGE ="com.springboot.dao.second"; staticfinalString MAPPER_LOCATION ="classpath:mapper/second/*.xml";@Value("${second.datasource.url}")privateString url;@Value("${second.datasource.username}")privateString user;@Value("${second.datasource.password}")privateString password;@Value("${second.datasource.driverClassName}")privateString driverClass;@Bean(name ="secondDataSource")publicDataSource clusterDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driverClass); dataSource.setUrl(url); dataSource.setUsername(user); dataSource.setPassword(password);returndataSource; }@Bean(name ="secondTransactionManager")publicDataSourceTransactionManager clusterTransactionManager() {returnnew DataSourceTransactionManager(clusterDataSource()); }@Bean(name ="secondSqlSessionFactory")publicSqlSessionFactory clusterSqlSessionFactory(@Qualifier("secondDataSource")DataSource clusterDataSource) throws Exception {finalSqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(clusterDataSource); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(SecondDataSourceConfig.MAPPER_LOCATION));returnsessionFactory.getObject(); }}
到此,不同的数据源配置就已经完成,剩下的只需要将将Mybatis的xml文件和DAO层的接口写好,并在Service层注入,直接使用就行。
Service层的代码:
@ServicepublicclassUserServiceImplimplementsUserService{@AutowiredprivateUserDao userDao;@AutowiredprivateSchoolDao schoolDao;publicUserVogetUser(Long id){ UserVo userVo = userDao.findById(id); SchoolVo schoolVo = schoolDao.findByName("清华"); userVo.setSchoolVo(schoolVo);returnuserVo; }}
Mybatis的xml文件UserDao.xml和SchoolDao.xml的内容:
UserDao.xml
id, user_nameselectfromuserwhereid = #{id}
SchoolDao.xml
id, school_name, school_describeselectfromschoolwhereschool_name = #{schoolName}
TestController
@Controller@RequestMapping(value ="/api/v1/test")public class TestController {@Autowiredprivate UserService userService;@RequestMapping(value ="/getUser")@ResponseBodypublic UserVo getUser(@RequestParam(value ="id") Long id) {returnuserService.getUser(id); }}
创建数据库和表SQL:
CREATEDATABASEspringbootdb;CREATEDATABASEspringbootdb_second;CREATETABLE`user`(`id`int(10)unsignedNOTNULLAUTO_INCREMENTCOMMENT'用户编号',`user_name`varchar(25)DEFAULTNULLCOMMENT'用户名称',`description`varchar(25)DEFAULTNULLCOMMENT'描述', PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=2DEFAULTCHARSET=utf8CREATETABLE`school`(`id`bigint(20)NOTNULL,`school_name`varchar(64)DEFAULTNULLCOMMENT'学校名',`school_describe`varchar(128)DEFAULTNULLCOMMENT'学校描述', PRIMARYKEY(`id`))ENGINE=InnoDBDEFAULTCHARSET=utf8insertinto`springbootdb`.`user`(`user_name`,`description`)values('shuai','so handsome');insertinto`springbootdb_second`.`school`(`id`,`school_name`,`school_describe`)values('1','清华','自强不息,厚德载物');
创建好数据后,整个工程的机构如下:
启动程序,在浏览器输入:http://localhost:8080/api/v1/test/getUser?id=1即可返回结果。