springboot项目连接多种数据库该如何操作详析

 更新时间:2024年08月01日 10:01:56   作者:不柔情  
在Spring Boot应用中连接多个数据库或数据源可以使用多种方式,下面这篇文章主要给大家介绍了关于springboot项目连接多种数据库该如何操作的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

前言

在项目的开发中,经常会遇到需要连接多个多种数据库的情况,mysql、oracle等等,下面详细讲解如何在一个服务中进行多种数据库的配置。

第一步:

在yml配置文件中配置多个数据源,如下,根据实际情况更改自己的配置即可。

spring:
  datasource:
    # 配置多个数据源
    primary:
      type: com.alibaba.druid.pool.DruidDataSource
      jdbc-url: jdbc:oracle:thin:@171.28.7.55:1521:example
      username: root
      password: root
      driver-class-name: oracle.jdbc.OracleDriver  #数据库链接驱动
    secondary:
      type: com.alibaba.druid.pool.DruidDataSource
      jdbc-url: jdbc:mysql://127.0.0.1:3306/exinfo?useUnicode=true&characterEncoding=utf-8
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver  #数据库链接驱动

第二步:

创建多个配置类,以配置oracle和mysql两个数据库为例,可参考代码进行延展。

1.在配置类中需要进行数据源配置

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    @Primary
    public DataSource db1DataSource() {
        return DataSourceBuilder.create().build();
    }
@ConfigurationProperties(prefix = "spring.datasource.primary")用于绑定yml中的第一个数据源配置,这些配置项会被自动映射到db1DataSource所创建的数据源实例中。通过DataSourceBuilder. create()创建一个新的数据源构建器,并调用.build()方法来完成数据源实例的创建。

如果有多个相同类型的Bean,使用@Primary注解可以标记出一个优先(默认)使用的Bean。所以使用最多的数据库可以使用@Primary注解。

2.配置MyBatis的SqlSessionFactory,它是MyBatis操作数据库的核心组件,负责创建SqlSession对象,执行SQL语句等。使用名称为db1DataSource的数据源Bean作为构造SqlSessionFactory的依赖。

    @Bean
    @Primary
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);//设置下划线转驼峰式
        return bean.getObject();
    }

3.配置事务管理器(DataSourceTransactionManager),它基于数据源(DataSource)的事务管理实现,专门用于JDBC事务处理。注解明确指定使用名为db1DataSource的数据源Bean。

    @Bean
    @Primary
    public DataSourceTransactionManager db1TransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

4.配置SqlSessionTemplate实例,它是MyBatis与Spring集成的关键组件,提供了线程安全的SQL会话执行环境。

    @Bean
    @Primary
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

5.类注解@MapperScan

  • basePackages= "com.example.mapper":指定了Mapper接口所在的包路径。Spring会扫描这个包及其子包下的所有接口,如果接口符合MyBatis Mapper的规范,Spring会自动生成代理对象来处理SQL调用。
  • sqlSessionTemplateRef = "db1SqlSessionTemplate":指定了与Mapper接口绑定的sqlSessionTemplate的名称。在执行Mapper接口的方法时,Spring会使用这个指定的sqlSessionTemplate来管理SQL会话。这里的db1SqlSessionTemplate是之前通过@Bean方法定义的sqlSessionTemplate Beam的名称。

DataSourcePrimaryConfig完整代码如下:

package com.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.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.mapper", sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class DataSourcePrimaryConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    @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.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);//设置下划线转驼峰式
        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){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

DataSourceSecondaryConfig代码如下:

package com.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.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.mapper2", sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class DataSourceSecondaryConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    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.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);//设置下划线转驼峰式
        return bean.getObject();
    }

    @Bean
    public DataSourceTransactionManager db2TransactionManager(@Qualifier("db2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate db2SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

第三步:

根据配置文件,创建两个mapper包如下:

在不同的mapper包下进行不同数据库的交互即可。

总结

到此这篇关于springboot项目连接多种数据库该如何操作的文章就介绍到这了,更多相关springboot连接多种数据库内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 新手入门学习Spring Freemarker教程解析

    新手入门学习Spring Freemarker教程解析

    这篇文章主要介绍了新手入门学习Freemarker教程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • JAVA Static关键字的用法

    JAVA Static关键字的用法

    这篇文章主要介绍了JAVA Static关键字的用法,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-07-07
  • 解析Idea为什么不推荐使用@Autowired进行Field注入

    解析Idea为什么不推荐使用@Autowired进行Field注入

    这篇文章主要介绍了Idea不推荐使用@Autowired进行Field注入的原因,网上文章大部分都是介绍两者的区别,没有提到为什么,当时想了好久想出了可能的原因,今天来总结一下
    2022-05-05
  • Java进程内缓存框架EhCache详解

    Java进程内缓存框架EhCache详解

    这篇文章主要介绍了Java进程内缓存框架EhCache,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2021-12-12
  • SpringBoot浅析缓存机制之Redis单机缓存应用

    SpringBoot浅析缓存机制之Redis单机缓存应用

    在上文中我介绍了Spring Boot使用EhCache 2.x来作为缓存的实现,本文接着介绍使用单机版的Redis作为缓存的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • springboot下使用shiro自定义filter的个人经验分享

    springboot下使用shiro自定义filter的个人经验分享

    这篇文章主要介绍了springboot下使用shiro自定义filter的个人经验,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • 深入探究SpringBoot中的Elasticsearch自动配置原理及用法

    深入探究SpringBoot中的Elasticsearch自动配置原理及用法

    SpringBoot中的Elasticsearch自动配置为我们提供了一种快速集成Elasticsearch的方式,使我们可以在SpringBoot应用程序中轻松地使用Elasticsearch,本文将介绍Spring Boot中的Elasticsearch自动配置的作用、原理和使用方法
    2023-07-07
  • Maven基础之如何修改本地仓库的默认路径

    Maven基础之如何修改本地仓库的默认路径

    这篇文章主要介绍了Maven基础之如何修改本地仓库的默认路径问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05
  • Spring 框架中的 SseEmitter 使用原理解析

    Spring 框架中的 SseEmitter 使用原理解析

    SseEmitter是Spring MVC提供的一个类,用于实现基于HTTP的服务器单向推送(Server-Sent Events),本文给大家介绍Spring框架中的 SseEmitter使用详解,感兴趣的朋友跟随小编一起看看吧
    2026-02-02
  • Java下载https文件并上传阿里云oss服务器

    Java下载https文件并上传阿里云oss服务器

    这篇文章主要介绍了Java下载https文件并上传到阿里云oss服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01

最新评论