场景假设:现有电商业务,商品和库存分别放在不同的库

配置数据库连接

app:
datasource: first:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1/product?useSSL=false
username: root
password: root
configuration:
maximum-pool-size: 10 second:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1/stock?useSSL=false
username: root
password: root
configuration:
maximum-pool-size: 10

添加配置类

FirstConfig

@Configuration
@EnableJpaRepositories(
basePackages = {"com.karonda.springboot2datasourcesjpa.dao.first"},// 1. dao 层所在的包
entityManagerFactoryRef = "firstEntityManagerFactory",
transactionManagerRef = "firstTransactionManager")
@EnableTransactionManagement
public class FirstConfig { @Bean
@Primary
public PlatformTransactionManager firstTransactionManager() {
return new JpaTransactionManager(firstEntityManagerFactory().getObject());
} @Bean
@Primary
public LocalContainerEntityManagerFactoryBean firstEntityManagerFactory() { HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(firstDataSource());
factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
factoryBean.setJpaProperties(hibernateProperties()); factoryBean.setPackagesToScan("com.karonda.springboot2datasourcesjpa.entity.first");// 2. 实体类所在的包 return factoryBean;
} @Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
} @Bean
@Primary
@ConfigurationProperties("app.datasource.first.configuration")
public DataSource firstDataSource() {
return firstDataSourceProperties()
.initializeDataSourceBuilder()
.type(HikariDataSource.class) // 3. 可以显示指定连接池,也可以不显示指定;即此行代码可以注释掉
.build();
} private Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
// hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create");
return hibernateProperties;
} }

SecondConfig

@Configuration
@EnableJpaRepositories(
basePackages = {"com.karonda.springboot2datasourcesjpa.dao.second"},
entityManagerFactoryRef = "secondEntityManagerFactory",
transactionManagerRef = "secondTransactionManager")
@EnableTransactionManagement
public class SecondConfig { @Bean
public PlatformTransactionManager secondTransactionManager() {
return new JpaTransactionManager(secondEntityManagerFactory().getObject());
} @Bean
public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory() { HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(secondDataSource());
factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
factoryBean.setJpaProperties(hibernateProperties()); factoryBean.setPackagesToScan("com.karonda.springboot2datasourcesjpa.entity.second"); return factoryBean;
} @Bean
@ConfigurationProperties("app.datasource.second")
public DataSourceProperties secondDataSourceProperties() {
return new DataSourceProperties();
} @Bean
@ConfigurationProperties("app.datasource.second.configuration")
public DataSource secondDataSource() {
return secondDataSourceProperties()
.initializeDataSourceBuilder()
.type(HikariDataSource.class)
.build();
} private Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
// hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create");
return hibernateProperties;
} }

dao

public interface ProductDao extends JpaRepository<Product, Integer> {

    @Query(value = "select p from Product p where p.id = id")
Product findById(@Param("id") int id);
}
public interface StockDao extends JpaRepository<Stock, Integer> {

    @Query(value = "select s from Stock s where s.productId = productId")
Stock findByProductId(@Param("productId") int productId);
}

使用示例

@Component
public class Task { @Autowired
private ProductDao productDao;
@Autowired
private StockDao stockDao; @Scheduled(cron = "0/5 * * * * ? ")
public void job(){ final int productId = 1;
Product product = productDao.findById(productId);
Stock stock = stockDao.findByProductId(productId); System.out.println("产品名称: " + product.getName() + ", 库存: " + stock.getStockCount());
} }

注意事项

  1. 使用多数据源,其中一个配置类需要添加 @Primary 注解 (有且仅有一个配置类需要添加)
  2. 在配置类中需要同时配置 dao 层和实体类所在的包

参考:

完整代码:GitHub

本人 C# 转 Java 的 newbie, 如有错误或不足欢迎指正,谢谢

Spring Boot 2.x 多数据源配置之 JPA 篇的更多相关文章

  1. Spring Boot 2.x 多数据源配置之 MyBatis 篇

    场景假设:现有电商业务,商品和库存分别放在不同的库 配置数据库连接 app: datasource: first: driver-class-name: com.mysql.cj.jdbc.Drive ...

  2. 13、Spring Boot 2.x 多数据源配置

    1.13 Spring Boot 2.x 多数据源配置 完整源码: Spring-Boot-Demos

  3. Spring Boot之JdbcTemplate多数据源配置与使用

    之前在介绍使用JdbcTemplate和Spring-data-jpa时,都使用了单数据源.在单数据源的情况下,Spring Boot的配置非常简单,只需要在application.propertie ...

  4. spring boot +mybatis+druid 多数据源配置

    因为我的工程需要在两个数据库中操作数据,所以要配置两个数据库,我这里没有数据源没有什么主从之分,只是配合多数据源必须要指定一个主数据源,所以我就把 操作相对要对的那个数据库设置为主数据(dataBas ...

  5. Spring Boot 两种多数据源配置:JdbcTemplate、Spring-data-jpa

    多数据源配置 JdbcTemplate支持 Spring-data-jpa支持 多数据源配置 创建一个Spring配置类,定义两个DataSource用来读取application.propertie ...

  6. Spring Boot2 系列教程(二十)Spring Boot 整合JdbcTemplate 多数据源

    多数据源配置也算是一个常见的开发需求,Spring 和 SpringBoot 中,对此都有相应的解决方案,不过一般来说,如果有多数据源的需求,我还是建议首选分布式数据库中间件 MyCat 去解决相关问 ...

  7. Spring Boot应用的后台运行配置

    酱油一篇,整理一下关于Spring Boot后台运行的一些配置方式.在介绍后台运行配置之前,我们先回顾一下Spring Boot应用的几种运行方式: 运行Spring Boot的应用主类 使用Mave ...

  8. Spring boot 的 properties 属性值配置 application.properties 与 自定义properties

    配置属性值application.properties 文件直接配置: com.ieen.super.name="MDD" 自定义properties文件配置:src/main/r ...

  9. Spring Boot 启动(二) 配置详解

    Spring Boot 启动(二) 配置详解 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring Boot 配置 ...

随机推荐

  1. 【Luogu】P6232 [eJOI2019]挂架 题解

    这道题跟CSP/S 2019 D1T1有点像. 我们先来模拟一下 \(n=4\) 的情况, 不难得出,最后的衣架挂钩顺序: 下标: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 ...

  2. Git 2.20.1 安装及配置

    一.下载地址 https://git-scm.com/downloads   二.安装步骤1.windows 64bit1.1)双击 Git-2.20.1-64-bit.exe 安装 1.2)选择安装 ...

  3. ASP.NET Core框架揭秘[博文汇总-持续更新]

    第1部分 跨平台开发体验 1 跨平台开发体验 001 跨平台开发体验: Windows [上篇]         002 跨平台开发体验: Windows [中篇]        003 跨平台开发体 ...

  4. 安装node.js和vue

    1.在官网上下载Node.js安装包  https://nodejs.org/zh-cn/ 2.点击安装,一直下一步下一步就行,这里就不在赘述了. 3.安装完之后,如果没有选安装路径的话,一般都是在[ ...

  5. Internet 网络协议族

    1.linux目前支持多种协议族,每个协议族用一个net_porto_family结构实例来表示,在初始化时,会调用sock_register()函数初始化注册到net_families[NPROTO ...

  6. binary hacks读数笔记(共享库)

    共享库从文件结构上来讲,与共享对象没什么区别.Linux下,共享库就是普通的ELF共享对象. 1.共享库命名: libname.so.x.y.z :其中最前面使用前缀lib,中间是库的名字和后缀&qu ...

  7. 1-03 Java的基本程序设计结构

    1-03 Java的基本程序设计结构 3.1 & 3.2 在一个单词中间使用大写字母的方式称为骆驼命名法.以其自身为例,应该写成CamelCase). 与C/C++一样,关键字void表示这个 ...

  8. 自动化测试_移动端测试(一) ----- Appium环境搭建

    一. 安装node.js 因为Appium是使用nodejs实现的,所以node是解释器,首先需要确认安装好 官网下载node.js:https://nodejs.org/en/download/ 安 ...

  9. Python_俄罗斯方块

    网上资料,仅供学习,希望以后自己也能看懂再改进下... """ 俄罗斯方块 author: wolfstar last edited: 2018年1月 "&qu ...

  10. Qiskit 安装指南

    内容参考官方文档 https://qiskit.org/documentation/install.html conda create -n name_of_my_env python=3 创建虚拟环 ...