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接口就可以实现多数据库连接了。
热门推荐
关节问题:迈之灵能否替代塞来昔布?
如何了解广州东站浅水湾的房产情况?这些情况对购房者有何影响?
歼轰36:全向隐身和速度我全都要,美国B21你也配叫六代机?
工资多少交个人所得税对不同地区有差异吗?
研究揭示:调整饮食模式或可延长中国人寿命超6年
感谢魔术!感谢范甘迪!39岁老魔兽入选魔术名人堂!
Spring配置文件详解:properties与yml的使用对比
SCI论文选题指南:从原则到案例的全面解析
硕士论文研究问题怎么确定
重磅!赛迪发布《量子产业发展白皮书(2024年)》
湖南现代罗马柱尺寸规格解析
如何在春天种植郁金香:技巧与注意事项详解
腌制泡菜的做法大全窍门(7种开胃下饭泡菜腌制方法)
买卖合同中的产品退货与退款规定
贷款还款Excel计算器制作指南
本周外盘看点丨美联储最关注通胀指标来袭!特朗普关税会否生变
烧纸钱与纸房子:跨越生死的情感纽带与文化传承
全科医生必备:RICE问诊原则与NURSE沟通技巧详解
在DEI热潮中反思"包容性":让每个孩子真正感到归属感
直饮机有水垢怎么回事 直饮机除水垢的方法
光纤损耗的类型及标准,如何计算光纤损耗?
橡胶木检测:从项目到流程的全面解析
如何优化自动仓储管理系统以提升物流效率?
糖化血红蛋白是检查什么的?了解这项指标的重要性
认识电脑的各大组件 【主板、CPU、内存条、硬盘、显卡、显示器】
电气安全检查如何进行
氮化镓功率集成电路通往可持续发展未来的道路
全球首次!九峰山实验室实现氮化镓材料制备领域新突破
2024年河南专升本还会扩招吗?扩招的方向有哪些?
耳机听不到声音怎么办?