Spring Boot 2.x 多数据源配置之 JPA 篇
场景假设:现有电商业务,商品和库存分别放在不同的库
配置数据库连接
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());
}
}
注意事项
- 使用多数据源,其中一个配置类需要添加 @Primary 注解 (有且仅有一个配置类需要添加)
- 在配置类中需要同时配置 dao 层和实体类所在的包
参考:
完整代码:GitHub
本人 C# 转 Java 的 newbie, 如有错误或不足欢迎指正,谢谢
Spring Boot 2.x 多数据源配置之 JPA 篇的更多相关文章
- Spring Boot 2.x 多数据源配置之 MyBatis 篇
场景假设:现有电商业务,商品和库存分别放在不同的库 配置数据库连接 app: datasource: first: driver-class-name: com.mysql.cj.jdbc.Drive ...
- 13、Spring Boot 2.x 多数据源配置
1.13 Spring Boot 2.x 多数据源配置 完整源码: Spring-Boot-Demos
- Spring Boot之JdbcTemplate多数据源配置与使用
之前在介绍使用JdbcTemplate和Spring-data-jpa时,都使用了单数据源.在单数据源的情况下,Spring Boot的配置非常简单,只需要在application.propertie ...
- spring boot +mybatis+druid 多数据源配置
因为我的工程需要在两个数据库中操作数据,所以要配置两个数据库,我这里没有数据源没有什么主从之分,只是配合多数据源必须要指定一个主数据源,所以我就把 操作相对要对的那个数据库设置为主数据(dataBas ...
- Spring Boot 两种多数据源配置:JdbcTemplate、Spring-data-jpa
多数据源配置 JdbcTemplate支持 Spring-data-jpa支持 多数据源配置 创建一个Spring配置类,定义两个DataSource用来读取application.propertie ...
- Spring Boot2 系列教程(二十)Spring Boot 整合JdbcTemplate 多数据源
多数据源配置也算是一个常见的开发需求,Spring 和 SpringBoot 中,对此都有相应的解决方案,不过一般来说,如果有多数据源的需求,我还是建议首选分布式数据库中间件 MyCat 去解决相关问 ...
- Spring Boot应用的后台运行配置
酱油一篇,整理一下关于Spring Boot后台运行的一些配置方式.在介绍后台运行配置之前,我们先回顾一下Spring Boot应用的几种运行方式: 运行Spring Boot的应用主类 使用Mave ...
- Spring boot 的 properties 属性值配置 application.properties 与 自定义properties
配置属性值application.properties 文件直接配置: com.ieen.super.name="MDD" 自定义properties文件配置:src/main/r ...
- Spring Boot 启动(二) 配置详解
Spring Boot 启动(二) 配置详解 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring Boot 配置 ...
随机推荐
- C#5语法新特性
C# 5.NET Framework 4.5 Visual Studio 2012 C#5.0新引进的语法基于.Net Framework 4.5.主要引进的语法:异步与等待,调用方信息 其中最重要的 ...
- 6 MVVM进阶
1. 背景 MVVM是一种常用的设计模式,它的最主要功能是将数据与代码隔离,实现viewmodel的可测试.架构图如下: 2. 命令-Command 2.1 WPF 路由命令 WPF提供一种内置的命令 ...
- Table is marked as crashed and should be repaired 解决办法
遇到这个问题几个敲命令轻松搞定 1.首先进入mysql命令台: mysql -u root -p 回车 输入密码 2.查询所有的库 mysql> show databases; 3.进入数据库 ...
- Spider_基础总结4_bs.find_all()与正则及lambda表达式
# beautifulsoup的 find()及find_all()方法,也会经常和正则表达式以及 Lambda表达式结合在一起使用: # 1-bs.find_all()与正则表达式的应用: # 语法 ...
- 仿select下拉框
默认状态下,灰色面板出现.当点击页面按钮以及灰色面板外区域时,面板消失;点击按钮,灰色面板出现;点击灰色面板区域,面板不能消失. 主要考察:事件冒泡与取消事件冒泡. 代码: <!DOCTYPE ...
- zabbix 告警实践分享 一键实现zabbix 电话、邮件、微信告警
众所周知Zabbix 是一款用来监控IT基础设施的监控套件,同时也具有很多方便运维人员使用的优秀功能,如:支持多条件告警,支持多种告警方式,支持多组模板.支持模板继承,因此在众多的开源运维监控软件中独 ...
- UNP——第六章,多路转接IO——select
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); ...
- JLC PCB 嘉立创自动确认生产稿,不讲武德?耗子尾汁!!!
首先,开局一张图,嘉立创又不做人的一天.嘉立创不讲武德,耗子尾汁!!! 之前下单,勾选了确定生产稿和不加客编,结果生产稿出来还是给我加了客编.那我出10元的意思何在?让我自己花3元看我花的10元有没有 ...
- 每天一个linux命令之stat
[Linux]Linux下使用stat命令所显示出来的三个时间 转 https://blog.csdn.net/pointer_y/article/details/54347968 在linux系统下 ...
- HDU100题简要题解(2000~2009)
前言(废话): 从11月6号到11月20号,断断续续做了有三个星期,总算整完了,之后会慢慢整理汇总到这里 中间部分用到数学知识的十几道题边学边做直接把我这个数学菜鸟做到怀疑人生 11.6~11.10又 ...