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接口就可以实现多数据库连接了。
热门推荐
这个「好习惯」,正在偷偷伤害你的皮肤!
湖南省哪个市最富?湖南各市经济实力排名
5个月未见,老虎·伍兹都说了什么?
火电厂节能减排的重要性及策略
运动营养食品不是“万能药”,这样补充才科学
泰安市妇幼保健院:白内障早期信号与防治—从此不再“雾里看花”
新城市志丨打造“全球最大的人工智能孵化器”,上海为什么能
张惠妹「ASMR MAX」巡回演唱会青岛站圆满落幕
999皮炎平三种类型详解:成分、功效与使用注意事项
最新电影下载6v:全面解析与合法观影指南
“备胎歌神”李圣杰:出道的十八年,不如在周杰伦演唱会上的一分钟
消费者剩余的重要性及其对市场的影响分析
男命八字格局深度解析:五大格局详解揭秘
90后女律师:法治事业中的新生力量
TikTok网红如何影响品牌营销?揭秘成功带货策略
7月西藏拉萨旅游全攻略:交通、住宿、景点门票一文详解
城市越多人,电动车越多
二战时日本以本国军力对抗整个亚洲及世界,其原因和背景是什么
5岁儿童体检一般做哪些项目
三门之战:明朝柘林叛军的末日
为什么乌龟是飘着的?
Nature揭秘:睡眠时大脑如何深度加工记忆
手机游戏渐成“健康杀手”专家提醒娱乐需适度
中国科学家揭示森林生物多样性维持新机制
城市污水余氯检测方法与检测意义
浅析壮锦纹样的传承与创新
电脑超频是什么意思?超频的好处与坏处全解析
宝藏小城营口,探索博物馆背后的历史秘密!
如何根据脸型挑选最合适的男生发型,焕然一新发型推荐攻略
怎么治疗早期复极综合征