Spring Boot连接两个数据库(以MySQL和H2数据库为例)
创作时间:
作者:
@小白创作中心
Spring Boot连接两个数据库(以MySQL和H2数据库为例)
引用
CSDN
1.
https://blog.csdn.net/weixin_56213139/article/details/140008729
在Spring Boot项目中,有时需要连接多个数据库来处理不同类型的数据。本文以MySQL和H2数据库为例,详细介绍如何在Spring Boot项目中配置和使用两个数据源。
一、项目结构
相比于原版的项目,如果需要连接两个数据库则需要创建两个文件夹,分别为config文件夹和mapper文件夹中新创立的baseMapper和testMapper文件夹,分别存放Mysql数据中的查询语句和H2的查询语句。
如果不是在Mapper中以注释的方式写查询语句,就可以在resources文件夹的xml文件中修改mapper中namespace的位置,如下图:
二、所需依赖
在pom.xml
文件中添加以下依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.3</version>
</parent>
<groupId>org.example</groupId>
<artifactId>big-event</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>big-event</name>
<url>http://maven.apache.org</url>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.3</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.example</groupId>-->
<!-- <artifactId>multipleDataConnection</artifactId>-->
<!-- <version>1.0-SNAPSHOT</version>-->
<!-- </dependency>-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.1.3</version>
</plugin>
</plugins>
</build>
</project>
三、具体配置
在config
文件夹中分别创建DataSourceOneConfig
和DataSourceTwo
两个文件,分别存放MySQL和H2的数据库配置,其中需要根据自己项目的具体配置来改写MapperScan
和getResources
中的mapper路径,配置的具体代码如下。
DataSourceOneConfig:
package org.example.config;
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.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.mybatis.spring.annotation.MapperScan;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "org.example.mapper.baseMapper", sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class DataSourceOneConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.one")
@Primary
public DataSource db1DataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@Primary
public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:org/example/mapper/*.xml"));
return bean.getObject();
}
@Bean
@Primary
public DataSourceTransactionManager db1TransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
@Primary
public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
DataSourceTwoConfig:
package org.example.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.mybatis.spring.annotation.MapperScan;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "org.example.mapper.testMapper", sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class DataSourceTwoConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.two")
public DataSource db2DataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory db2SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
return bean.getObject();
}
@Bean
public DataSourceTransactionManager db2TransactionManager(@Qualifier("db2DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public SqlSessionTemplate db2SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
创建好以上配置文件后,在application.yml
中添加第二个数据库配置,如下:
spring:
datasource:
one:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/big_event
username: root
password: 7777777
two:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: org.h2.Driver
jdbc-url: jdbc:h2:tcp://localhost:10007/node
username: sa
password:
完成以上步骤后,在mapper中创建相应的文件夹,放入对应的Mapper接口(此处包的名称一定要和之前在config中配置的一样):
以上步骤均完成后,再调用不同包中的Mapper接口就可以实现多数据库连接了。
热门推荐
爵士贝斯入门指南:从基础技巧到即兴演奏
宠物猫咪分娩全程指南:注意事项与解决方案
11个腹肌锻炼动作升级指南,避免常见误区,追求更高效的核心力量训练。
骑马与砍杀2:玩转管理学技能,快速提升势力
男宝宝起名艺术,传承文化与个性
黄帝有哪些贡献,对后世有什么影响?黄帝的地位是什么?
烽火长歌:国军十大名将的军事传奇与人生终章
插混车VS增程车,谁才是最远行者?
济南轨道交通3号线二期新进展:正在试运行,向年内通车目标冲刺
怎么验证excel上传格式
上海开车到绍兴要多久?2024最新攻略,让你一路畅通无阻,享受驾驶的乐趣!
部分城市居民医保收支平衡压力加大,筹资机制如何完善
演唱会探索融合展览游乐新模式
负面情绪漫画:探索情感深处的治愈力量
电脑频繁重启怎么办?四种实用解决方案帮你轻松应对
绿芦笋、白芦笋差在哪?芦笋营养不只有叶酸,2道芦笋料理简单好上手
重回国王!福克斯揭秘真相:我只加盟马刺,没有其他!
独自旅行:自由探索与自我成长的心灵之旅
尿液颜色与健康的关系:从正常到异常的全面解析
数学建模算法与应用 第6章 微分方程建模及其求解方法
东莞古村焕新颜:历史与现代交织的璀璨光彩
一岁的边牧应该吃什么?(科学饲养指南帮助您为宠物狗提供 ...
期货市场价格波动原因分析及投资策略
强基计划怎样才能入围?附2025入围规则及计算方法
超高速磁悬浮、水上巴士、地铁6号线……南宁新一轮综合交通规划公示
吃了过期的方便面会怎么样?你敢吃吗?别再冒险了!
为什么以前很火的青天大老爷包青天的电视剧,现在几乎没人拍了?
骑摩托车对身心健康有哪些益处?
三国中的武圣:关羽的地位与影响
光纤布拉格光栅是怎样的?