【SpringBoot整合系列】SpringBoot配置多数据源

目录

  • 背景
    • 技术选型
    • 配置多数据源思路(以两个为例)
    • 代码实现
      • 1.导入依赖
      • 2.各自的配置
    • 3.各自的dataSource
      • news数据库的
      • smbms数据库的
      • 注意:@Primary注解
    • 4.各自的SqlSessionFactory等
      • news数据库的
      • smbms数据库的
    • 5.去掉启动类头上的@MapperScan
    • 6.各自的mapper接口
    • 7.各自的mapper.xml
    • 8.测试

背景

  • 在单数据源的情况下,Spring Boot的配置非常简单,只需要在application.properties文件中配置连接参数即可。
  • 但是往往随着业务量发展,我们通常会进行数据库拆分或是引入其他数据库,从而我们需要配置多个数据源

技术选型

  • SpringBoot2.3.12
  • jdk1.8
  • mysql5.7
  • 持久层框架mybatis

配置多数据源思路(以两个为例)

  1. 要执行两个数据库的操作,就需要有两个数据库配置
  2. 有两个数据库配置那就要两个SqlSessionBuilder来创建SqlSessionFactory
  3. 有两个SqlSessionFactory就能创建两个数据库自己的sqlSession
  4. 然后就能执行不同数据库的操作了
  5. 现在用的都是数据库连接池,需要创建dataSource,因此,按照上面的思路,也需要有各自数据库的dataSource
  6. 用各自的dataSource创建各自的SqlSessionFactory
  7. 继而创建各自的SqlSessionTemplate
  8. 当然,事务管理器也应该是用各自的dataSource来创建
  9. 那么,各自的SqlSessionFactory就要扫描各自的mapper层,因此就需要有各自的mapper包
  10. 至于各自的mapper.xml可以放在一起,也可以不放在一起,因为mapper.xml中的namespace是根据包名来映射的

代码实现

1.导入依赖

		<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.21</version></dependency><!-- 阿里数据库连接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.9</version></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.1</version></dependency>

2.各自的配置

server:port: 8888logging:level:org.springframework.web: debugcom.kgc.mapper: debug
spring:datasource:smbms:driverClassName: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/smbms?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghaiusername: rootpassword: 123456news:driverClassName: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/chinanewsdb?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghaiusername: rootpassword: 123456mybatis:mapper-locations: classpath:mybatis/mapper/*.xmltype-aliases-package: com.kgc.pojonews:mapper-locations: classpath:mybatis/newsmapper/*.xml
#  configuration:
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

在这里插入图片描述

3.各自的dataSource

news数据库的

package com.kgc.config;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;import javax.sql.DataSource;/*** @author: zjl* @datetime: 2024/4/20* @desc:*/
@Configuration
//@ConfigurationProperties(prefix = "spring.datasource.news")
public class NewsDataSourceConfig {@Value("${spring.datasource.news.driverClassName}")private String driverClassName;@Value("${spring.datasource.news.url}")private String url;@Value("${spring.datasource.news.username}")private String username;@Value("${spring.datasource.news.password}")private String password;@Bean("newsDataSource")public DataSource createDataSource() {DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName(driverClassName);dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);return dataSource;}
}

smbms数据库的

package com.kgc.config;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;import javax.sql.DataSource;/*** @author: zjl* @datetime: 2024/4/20* @desc:*/
@Configuration
//@ConfigurationProperties(prefix = "spring.datasource.smbms")
public class SmbmsDataSourceConfig {@Value("${spring.datasource.smbms.driverClassName}")private String driverClassName;@Value("${spring.datasource.smbms.url}")private String url;@Value("${spring.datasource.smbms.username}")private String username;@Value("${spring.datasource.smbms.password}")private String password;@Bean("smbmsDataSource")@Primarypublic DataSource createDataSource() {DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName(driverClassName);dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);return dataSource;}
}

注意:@Primary注解

  • 其作用与功能,当有多个相同类型的bean时,使用@Primary来赋予bean更高的优先级。
  • 在这里,需要注册多个相同DataSource类型的bean,要有一个有更高的优先级,否则会报错

4.各自的SqlSessionFactory等

news数据库的

package com.kgc.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.beans.factory.annotation.Value;
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.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;import javax.annotation.Resource;
import javax.sql.DataSource;/*** @author: zjl* @datetime: 2024/4/20* @desc:*/
@Configuration
@EnableTransactionManagement
@MapperScan(value = "com.kgc.news.mapper",sqlSessionFactoryRef = "newsSqlSessionFactory")
public class NewsSqlSessionFactoryConfiguratiion {@Resource(name = "newsDataSource")private DataSource newsDataSource;@Value("${mybatis.news.mapper-locations}")private String mapperLocations;@Bean("newsSqlSessionFactory")public SqlSessionFactory create() throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(newsDataSource);PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();bean.setMapperLocations(resourcePatternResolver.getResources(mapperLocations));return bean.getObject();}@Bean("newsSqlSessionTemplate")public SqlSessionTemplate createSqlSession(@Qualifier("newsSqlSessionFactory") SqlSessionFactory sqlSessionFactory){return new SqlSessionTemplate(sqlSessionFactory);}@Bean("newsTransactionManager")public PlatformTransactionManager createTransactionManager(){return new DataSourceTransactionManager(newsDataSource);}
}

smbms数据库的

package com.kgc.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.beans.factory.annotation.Value;
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.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;/*** @author: zjl* @datetime: 2024/4/20* @desc:*/
@Configuration
@EnableTransactionManagement
@MapperScan(value = "com.kgc.mapper",sqlSessionFactoryRef = "smbmsSqlSessionFactory")
public class SmbmsSqlSessionFactoryConfiguratiion {@Resource(name = "smbmsDataSource")private DataSource smbmsDataSource;@Value("${mybatis.mapper-locations}")private String mapperLocations;@Bean("smbmsSqlSessionFactory")public SqlSessionFactory create() throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(smbmsDataSource);PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();bean.setMapperLocations(resourcePatternResolver.getResources(mapperLocations));return bean.getObject();}@Bean("smbmsSqlSessionTemplate")public SqlSessionTemplate createSqlSession(@Qualifier("smbmsSqlSessionFactory") SqlSessionFactory sqlSessionFactory){return new SqlSessionTemplate(sqlSessionFactory);}@Bean("smbmsTransactionManager")public PlatformTransactionManager createTransactionManager(){return new DataSourceTransactionManager(smbmsDataSource);}
}

5.去掉启动类头上的@MapperScan

@SpringBootApplication
//@MapperScan(basePackages = {"com.kgc.mapper"})
public class BootdemoApplication {public static void main(String[] args) {SpringApplication.run(BootdemoApplication.class, args);}
}

6.各自的mapper接口

在这里插入图片描述

public interface UserMapper {int selectCount();
}
public interface NewsMapper {int selectCount();
}

7.各自的mapper.xml

在这里插入图片描述

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kgc.mapper.UserMapper"><select id="selectCount" resultType="int">SELECT COUNT(1) FROM SMBMS_USER</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kgc.news.mapper.NewsMapper"><select id="selectCount" resultType="int">SELECT COUNT(1) FROM news_detail</select>
</mapper>

8.测试

service

@Service
public class UserService {@Resourceprivate UserMapper userMapper;@Resourceprivate NewsMapper newsMapper;public Integer allCount(){return userMapper.selectCount() + newsMapper.selectCount();}
}

controller

@RestController
public class UserController {@Resourceprivate UserService userService;@RequestMapping("/all")public Object all(){return userService.allCount();}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/644303.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

齐护K210系列教程(八)_LCD显示图片

LCD显示图片 文章目录 LCD显示图片1&#xff0c;显示单张图片2&#xff0c;通过按键切换显示SD卡内的图片3&#xff0c;通过传感器切换图片4&#xff0c;画中画显示&#xff0c;并缩放5&#xff0c;课程资源 联系我们 AIstart 显示的图片的默认分辨率为&#xff1a;320*240 &am…

「ChatGPT」掀起新一轮AI热潮!超越GPT-4 Turbo,商汤日日新大升级!

目录 拳打 GPT-4 Turbo &#xff0c;脚踢 DALLE 3 端侧大模型&#xff0c;唯快不破 AI 应用落地需要一个即插即用的大模型超市 并不存在 AI 这个行业&#xff0c;只有 AI行业&#xff0c;强调 AI 需要与传统产业合作&#xff0c;这种关系是结合与赋能&#xff0c;而不是颠覆…

VS窗口固定尺寸的方法

Dialog每次都要找窗口尺寸固定的设置&#xff0c;因此在这个地方做个笔记 下次就好检索了。年级大了 脑子不够用了。

Qt : Windows剪切板监控

简介 偶然需要记录一下我的剪切内容&#xff0c; 在我完成所有剪切之后将内容存储到文件&#xff0c;这里使用到Qt5.15.2&#xff0c; 下面我们就来看看是怎么做的吧。 实现 代码 // 获取剪切板对象 clipboard QApplication::clipboard();// 连接剪切板内容变化信号到槽函数…

flutter笔记-万物皆是widget

文章目录 helloFlluter自定义Widget优化 这篇文章后就不见写了&#xff0c;学flutter主要是为了更好的使用 flutter-webrtc&#xff0c;所以到这里基本就了解了大部分的知识&#xff0c;后续边用边查&#xff1b; 在flutter中所有的view都叫widget&#xff0c;类似文本组件Tex…

蓝桥杯-网络安全-练习题-crypto-rsa

共模攻击 直接脚本即可 import libnum import gmpy2import random random.seed(123456)e1 random.randint(100000000, 999999999) print(e1) e2 65537 n 7265521127830448713067411832186939510560957540642195787738901620268897564963900603849624938868472135068795683…

618买什么最划算?618买什么东西便宜?必备数码好物清单分享

​只不&#xff0c;马上又到了618购物节咯&#xff0c;数码产品的优惠力度尤为显著&#xff0c;是购买数码产品的绝佳时机。接下来&#xff0c;我将为大家分享几款性价比超高的数码产品&#xff0c;相信总有一款能吸引你的目光。 一、南卡OE MIX开放式蓝牙耳机 在618购物狂欢节…

【vue2】实现微信截图(复制图片)在项目内可粘贴

需求 后台管理在上传图片地方需要将复制的图片粘贴上传 一、添加事件 在原有上传组件的基础上添加 paste事件 二、方法 onPaste(e) {const items (e.clipboardData || window.clipboardData).items;let blob null;for (let i 0; i < items.length; i) {if (items[i].ty…

【氧化镓】影响Ga2O3器件沟道载流子迁移率的关键因素

总结 这篇文章对β-Ga2O3 MOSFETs中的通道载流子迁移率进行了深入研究&#xff0c;通过实验测量和理论分析&#xff0c;揭示了影响迁移率的关键因素&#xff0c;特别是库仑散射的影响。研究结果对于理解和改进β-Ga2O3 MOSFETs的性能具有重要意义&#xff0c;为未来的研究和器…

混沌工程理论建设和项目实践

混沌工程理论建设和项目实践 1. 背景说明2. 为什么要做混沌工程2.1 混沌目标2.2 演习对象2.3 影响可用性的主要因素及应对2.4 可行性论证和控制爆炸半径 3. 如何落地3.1 安全、有效的实验3.2 安全&#xff1a;不影响线上业务3.2.1 爆炸半径3.2.2 特殊限制与审批 3.3 有效&#…

【FX110网】股市、汇市一年有多少个交易日?

事实上&#xff0c;作为交易者&#xff0c;重要的是要了解并非每天都是交易日。虽然金融市场在大多数工作日开放交易&#xff0c;但在某些特定情况下无法进行交易。这些非交易日可能因各种原因而发生&#xff0c;包括节假日、周末和市场休市。 通过随时了解假期、交易时间表和市…

【树莓派学习】开发环境配置

【树莓派学习】开发环境配置 ​ Raspberry Pi OS作为基于Linux的系统&#xff0c;其默认网络配置在国内的网络环境下容易出现访问慢甚至无法连接等问题&#xff0c;不便于我们的学习&#xff0c;同时&#xff0c;树莓派上C/C的使用需要单独安装WiringPi。本文主要介绍如何更改…