Springboot配置连接两个数据库
背景:
项目中需要从两个不同的数据库查询数据,之前实现方法是:springboot配置连接一个数据源,另一个使用jdbc代码连接。
为了改进,现在使用SpringBoot配置连接两个数据源
实现效果:
一个SpringBoot项目,同时连接两个数据库:比如一个是pgsql数据库,一个是oracle数据库
(啥数据库都一样,连接两个同为oracle的数据库,或两个不同的数据库,只需要更改对应的driver-class-name和jdbc-url等即可)
注意:连接什么数据库,要引入对应数据库的包
实现步骤:
1、修改application.yml,添加一个数据库连接配置
(我这里是yml格式,后缀为properties格式是一样的)
server:
port: 7101
spring:
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的配置文件

(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);
}
}
主数据库都有 @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
@Component
public interface TestDao1 { List<DailyActivityDataMiddle> selectDailyActivity(); }
(2)TestDao2.java
@Component
public interface TestDao2 { List<MovieShowTest> selectDailyActivity(); }
4、 在resource下新建test1和test2两个文件夹,分别放入对应dao层的xml文件
(我原来项目的dao的xml文件在resource目录下,你们在自己的项目对应目录下即可)
注意dao的java文件和dao的xml文件名字要一致

(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,分别查询数据
@RestController
public 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配置连接两个数据库的更多相关文章
- Linq to Entity中连接两个数据库时要注意的问题
Linq to Entity中连接两个数据库时要注意的问题 今天大学同学问了我一个问题,Linq to Entity中连接两个数据库时,报错“指定的 LINQ 表达式包含对与不同上下文关联的查询的引用 ...
- Android 通过外键连接两个数据库
Learn: 1.Android数据库的语法. 2.通过外键连接两个数据库. 3.加强了对数据库的熟悉度. 4.对文本框的visiblity属性的了解. Demo:http://pan.baidu.c ...
- ssm 连接两个数据库
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...
- django配置连接多个数据库,自定义表名称
在项目tt下新建两个app,分别为app01.app02.配置app01使用default节点数据库:app02使用hvdb节点数据库(也可以配置app01下的model既使用default,也可以使 ...
- SpringMVC配置双数据源,一个java项目同时连接两个数据库
数据源在配置文件中的配置 请点击---> java架构师项目实战,高并发集群分布式,大数据高可用,视频教程 <pre name="code" class=" ...
- sqldbx配置连接Oracle 12C数据库
本地开发环境: Windows10 64位.Oracle 12C客户端 32位.sqlDBX (32位) =============================================== ...
- SpringBoot配置属性之Migration
SpringBoot配置属性系列 SpringBoot配置属性之MVC SpringBoot配置属性之Server SpringBoot配置属性之DataSource SpringBoot配置属性之N ...
- springboot入门系列(四):SpringBoot和Mybatis配置多数据源连接多个数据库
SpringBoot和Mybatis配置多数据源连接多个数据库 目前业界操作数据库的框架一般是 Mybatis,但在很多业务场景下,我们需要在一个工程里配置多个数据源来实现业务逻辑.在SpringBo ...
- DB数据源之SpringBoot+MyBatis踏坑过程(六)mysql中查看连接,配置连接数量
DB数据源之SpringBoot+MyBatis踏坑过程(六)mysql中查看连接,配置连接数量 liuyuhang原创,未经允许禁止转载 系列目录连接 DB数据源之SpringBoot+Mybati ...
随机推荐
- zabbix--监控MySQL性能
Zabbix 自带模板监控 MySQL 性能 通过自带的 Template DB MySQL 模板监控 MySQL 性能 具体步骤: 1)创建脚本存放目录并编辑脚本 # mkdir /etc/zabb ...
- httprunner学习7-extract提取content返回对象
前言 提取response返回的对象数据,用extract关键字.前面有关于token的取值,通过content.token取值. 本篇详细讲解如何从返回的json数据提取出想要的各种数据 conte ...
- ImportError: No module named wx
先检查下Python中是否有此模块 $ python >>> import wx ImportError: No module named wx wx模块的确没有安装. 要安装wx ...
- 使用ArcGIS for Server的Feature Access REST在线编辑图层
如何启用Feature Access可以参考以前写的一篇博客:http://www.cnblogs.com/oceanking/p/3895257.html 本文主要关注一个全是点的图层,我也不知道学 ...
- Java trycatch使用重试Retryer
重试的工具类 Guava-retrying 依赖 <!-- https://mvnrepository.com/artifact/com.github.rholder/guava-retryin ...
- linux 下如何添加一个用户,并给予用户root权限
分类专栏: Linux 1.添加用户,首先用adduser命令添加一个普通用户,命令如下: adduser tommy //添加一个名为tommy的用户 passwd tommy //修改密码 C ...
- learning shell check host dependent pkg
[Purpose] Shell script check host dependent pkg [Eevironment] Ubuntu 16.04 bash env ...
- Presto Infrastructure at Lyft
转载一篇关于 lyft presto 平台建设的实践 Overview Early in 2017 we started exploring Presto for OLAP use cases and ...
- 【ARC098F】Donation
[ARC098F]Donation 题面 atcoder 题意: 给定一张\(n\)个点,\(m\)条边的无向图.这张图的每个点有两个权值 \(a_i,b_i\). 你将会从这张图中选出一个点作为起点 ...
- 修改git log中的Date格式
默认的git log查看日志显示的格式如下: Date: Thu Aug 16 17:44:32 2018 +0800 说实话,真不太喜欢这种日期格式还是换成数值比较舒服一点.git bash中使 ...