iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Springboot怎么同时装配两个相同类型数据库
  • 147
分享到

Springboot怎么同时装配两个相同类型数据库

2023-06-25 15:06:55 147人浏览 安东尼
摘要

这篇文章给大家分享的是有关SpringBoot怎么同时装配两个相同类型数据库的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。同时装配两个相同类型数据库1.配置文件:spring:  profil

这篇文章给大家分享的是有关SpringBoot怎么同时装配两个相同类型数据库的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

同时装配两个相同类型数据库

1.配置文件:

spring:  profiles:    active: dev   datasource:    primary:      jdbc-url: jdbc:sqlserver://localhost:1111;DatabaseName=DB1      driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver      type: com.alibaba.druid.pool.DruidDataSource      username: root      passWord: root    secondary:      jdbc-url: jdbc:sqlserver://localhost:1111;DatabaseName=DB2      driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver      type: com.alibaba.druid.pool.DruidDataSource      username: root      password: root

2.配置类:

①主配置类:DataSourceConfigPrimary

@Configuration@MapperScan(basePackages = "com.message.dao.primary", sqlSessionFactoryRef = "primarySqlSessionFactory")public class DataSourceConfigPrimary {     // 将这个对象放入Spring容器中    @Bean(name = "primaryDataSource")    // 表示这个数据源是默认数据源    @Primary    // 读取application.properties中的配置参数映射成为一个对象    // prefix表示参数的前缀    @ConfigurationProperties(prefix = "spring.datasource.primary")    public DataSource getDateSourcePrimary()    {        return DataSourceBuilder.create().build();    }     @Bean(name = "primarySqlSessionFactory")    // 表示这个数据源是默认数据源    @Primary    // @Qualifier表示查找Spring容器中名字为test1DataSource的对象    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource datasource)            throws Exception    {        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();        bean.setDataSource(datasource);        bean.setMapperLocations(                // 设置mybatis的xml所在位置                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/primary/*.xml"));        return bean.getObject();    }     @Bean("primarySqlSessionTemplate")    // 表示这个数据源是默认数据源    @Primary    public SqlSessionTemplate primarySqlSessionTemplate(            @Qualifier("primarySqlSessionFactory") SqlSessionFactory sessionFactory)    {        return new SqlSessionTemplate(sessionFactory);    }}

②次配置类:DataSourceConfigSecondary

@Configuration@MapperScan(basePackages = "com.message.dao.secondary", sqlSessionFactoryRef = "secondarySqlSessionFactory")public class DataSourceConfigSecondary {    @Bean(name = "secondaryDataSource")    @ConfigurationProperties(prefix = "spring.datasource.secondary")    public DataSource getDateSource2()    {        return DataSourceBuilder.create().build();    }     @Bean(name = "secondarySqlSessionFactory")    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource datasource)            throws Exception    {        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();        bean.setDataSource(datasource);        bean.setMapperLocations(                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/secondary/*.xml"));        return bean.getObject();    }     @Bean("secondarySqlSessionTemplate")    public SqlSessionTemplate secondarySqlSessionTemplate(            @Qualifier("secondarySqlSessionFactory") SqlSessionFactory sessionFactory)    {        return new SqlSessionTemplate(sessionFactory);    }}

3.扫描XML

4.启动类:

@SpringBootApplication(scanBasePackages = {"com.lalal.*"})public class MessageApplication extends SpringBootServletInitializer {     public static void main(String[] args) {        SpringApplication.run(MessageApplication.class, args);    }     @Bean    public RestTemplate restTemplate(){        return new RestTemplate();    }}

配置连接两个或多个数据库

背景:

项目中需要从两个不同的数据库查询数据,之前实现方法是:springboot配置连接一个数据源,另一个使用jdbc代码连接。

为了改进,现在使用SpringBoot配置连接两个数据源

实现效果:

一个SpringBoot项目,同时连接两个数据库:比如一个是pgsql数据库,一个是oracle数据库

(啥数据库都一样,连接两个同为oracle的数据库,或两个不同的数据库,只需要更改对应的driver-class-name和jdbc-url等即可)

注意:连接什么数据库,要引入对应数据库的包

实现步骤:

1、修改application.yml,添加一个数据库连接配置

(我这里是yml格式,后缀为properties格式是一样的

server:  port: 7101spring:  jpa:    show-sql: true  datasource:    test1:      driver-class-name: org.postgresql.Driver      jdbc-url: jdbc:postgresql://127.0.0.1:5432/test  #测试数据库      username: root      password: root     test2:      driver-class-name: oracle.jdbc.driver.OracleDriver      jdbc-url: jdbc:oracle:thin:@127.0.0.1:8888:orcl  #测试数据库      username: root      password: root

特别注意:

(1)使用test1、test2区分两个数据库连接

(2)url改为:jdbc-url

2、使用代码进行数据源注入,和扫描dao层路径(以前是在yml文件里配置mybatis扫描dao的路径)

新建config包,包含数据库1和数据库2的配置文件

Springboot怎么同时装配两个相同类型数据库

(1)第一个数据库作为主数据库,项目启动默认连接此数据库

DataSource1Config.java

package com.test.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 javax.sql.DataSource; @Configuration@MapperScan(basePackages = "com.test.dao.test1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")public class DataSource1Config {     @Bean(name = "test1DataSource")    @ConfigurationProperties(prefix = "spring.datasource.test1")    @Primary    public DataSource testDataSource() {        return DataSourceBuilder.create().build();    }     @Bean(name = "test1SqlSessionFactory")    @Primary    public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();        bean.setDataSource(dataSource);        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:test1/*.xml"));        return bean.getObject();    }     @Bean(name = "test1TransactionManager")    @Primary    public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {        return new DataSourceTransactionManager(dataSource);    }     @Bean(name = "test1SqlSessionTemplate")    @Primary    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {        return new SqlSessionTemplate(sqlSessionFactory);    }}

特别注意:

(1)主数据库都有 @Primary注解,从数据库都没有

(2)第二个数据库作为从数据库

DataSource2Config.java

package com.test.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.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; @Configuration@MapperScan(basePackages = "com.test.dao.test2", sqlSessionTemplateRef  = "test2SqlSessionTemplate")public class DataSource2Config {     @Bean(name = "test2DataSource")    @ConfigurationProperties(prefix = "spring.datasource.test2")    public DataSource testDataSource() {        return DataSourceBuilder.create().build();    }     @Bean(name = "test2SqlSessionFactory")    public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception {        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();        bean.setDataSource(dataSource);        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:test2/*.xml"));        return bean.getObject();    }     @Bean(name = "test2TransactionManager")    public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {        return new DataSourceTransactionManager(dataSource);    }     @Bean(name = "test2SqlSessionTemplate")    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {        return new SqlSessionTemplate(sqlSessionFactory);    }}

3、 在dao文件夹下,新建test1和test2两个包,分别放两个不同数据库的dao层文件

(1)TestDao1.java

@Componentpublic interface TestDao1 {     List<DailyActivityDataMiddle> selectDailyActivity(); }

(2)TestDao2.java

@Componentpublic interface TestDao2 {     List<MovieShowTest> selectDailyActivity(); }

4、 在resource下新建test1和test2两个文件夹,分别放入对应dao层的xml文件

(我原来项目的dao的xml文件在resource目录下,你们在自己的项目对应目录下即可)

注意dao的java文件和dao的xml文件名字要一致

Springboot怎么同时装配两个相同类型数据库

(1)TestDao1.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        "Http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.test.dao.test1.TestDao1">     <select id="selectDailyActivity" resultType="com.test.pojo.DailyActivityDataMiddle">         SELECT * FROM daily_activity_data_middle     </select> </mapper>

(2)TestDao2.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.test.dao.test2.TestDao2">     <select id="selectDailyActivity" resultType="com.test.pojo.MovieShowTest">         SELECT * FROM movieshowtest     </select> </mapper>

5、测试

在controller文件里,注入两个数据库的dao,分别查询数据

@RestControllerpublic class TestController extends BaseController{     @Autowired    private PropertiesUtils propertiesUtils;     @Autowired    private TestDao1 testDao1;     @Autowired    private TestDao2 testDao2;     @RequestMapping(value = {"/test/test1"},method = RequestMethod.POST)    public Result<JSONObject> DataStatistics (@RequestBody jsONObject body) throws Exception {        Result<JSONObject> result = new Result<>(ICommon.SUCCESS, propertiesUtils.get(ICommon.SUCCESS));         JSONObject object = new JSONObject();        object.put("data",testDao1.selectDailyActivity());        result.setResult(object);        return result;    }     @RequestMapping(value = {"/test/test2"},method = RequestMethod.POST)    public Result<JSONObject> DataStatisticsaa (@RequestBody JSONObject body) throws Exception {        Result<JSONObject> result = new Result<>(ICommon.SUCCESS, propertiesUtils.get(ICommon.SUCCESS));         JSONObject object = new JSONObject();        object.put("data",testDao2.selectDailyActivity());        result.setResult(object);        return result;    }}

感谢各位的阅读!关于“Springboot怎么同时装配两个相同类型数据库”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

--结束END--

本文标题: Springboot怎么同时装配两个相同类型数据库

本文链接: https://www.lsjlt.com/news/305764.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • C++ 生态系统中流行库和框架的贡献指南
    作为 c++++ 开发人员,通过遵循以下步骤即可为流行库和框架做出贡献:选择一个项目并熟悉其代码库。在 issue 跟踪器中寻找适合初学者的问题。创建一个新分支,实现修复并添加测试。提交...
    99+
    2024-05-15
    框架 c++ 流行库 git
  • C++ 生态系统中流行库和框架的社区支持情况
    c++++生态系统中流行库和框架的社区支持情况:boost:活跃的社区提供广泛的文档、教程和讨论区,确保持续的维护和更新。qt:庞大的社区提供丰富的文档、示例和论坛,积极参与开发和维护。...
    99+
    2024-05-15
    生态系统 社区支持 c++ overflow 标准库
  • c++中if elseif使用规则
    c++ 中 if-else if 语句的使用规则为:语法:if (条件1) { // 执行代码块 1} else if (条件 2) { // 执行代码块 2}// ...else ...
    99+
    2024-05-15
    c++
  • c++中的继承怎么写
    继承是一种允许类从现有类派生并访问其成员的强大机制。在 c++ 中,继承类型包括:单继承:一个子类从一个基类继承。多继承:一个子类从多个基类继承。层次继承:多个子类从同一个基类继承。多层...
    99+
    2024-05-15
    c++
  • c++中如何使用类和对象掌握目标
    在 c++ 中创建类和对象:使用 class 关键字定义类,包含数据成员和方法。使用对象名称和类名称创建对象。访问权限包括:公有、受保护和私有。数据成员是类的变量,每个对象拥有自己的副本...
    99+
    2024-05-15
    c++
  • c++中优先级是什么意思
    c++ 中的优先级规则:优先级高的操作符先执行,相同优先级的从左到右执行,括号可改变执行顺序。操作符优先级表包含从最高到最低的优先级列表,其中赋值运算符具有最低优先级。通过了解优先级,可...
    99+
    2024-05-15
    c++
  • c++中a+是什么意思
    c++ 中的 a+ 运算符表示自增运算符,用于将变量递增 1 并将结果存储在同一变量中。语法为 a++,用法包括循环和计数器。它可与后置递增运算符 ++a 交换使用,后者在表达式求值后递...
    99+
    2024-05-15
    c++
  • c++中a.b什么意思
    c++kquote>“a.b”表示对象“a”的成员“b”,用于访问对象成员,可用“对象名.成员名”的语法。它还可以用于访问嵌套成员,如“对象名.嵌套成员名.成员名”的语法。 c++...
    99+
    2024-05-15
    c++
  • C++ 并发编程库的优缺点
    c++++ 提供了多种并发编程库,满足不同场景下的需求。线程库 (std::thread) 易于使用但开销大;异步库 (std::async) 可异步执行任务,但 api 复杂;协程库 ...
    99+
    2024-05-15
    c++ 并发编程
  • 如何在 Golang 中备份数据库?
    在 golang 中备份数据库对于保护数据至关重要。可以使用标准库中的 database/sql 包,或第三方包如 github.com/go-sql-driver/mysql。具体步骤...
    99+
    2024-05-15
    golang 数据库备份 mysql git 标准库
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作