spring - 具有相同实体和存储库的多个数据源

标签 spring spring-boot spring-data-jpa multi-tenant

目前正在处理我的 Spring Boot 项目需要的项目
在同一数据库服务器中利用多个数据源或模式。我有
在中找到了几个教授多数据源配置的教程
spring boot,其中实体 foo 存在于数据源 A 中,而 bar 存在于
数据源B即如下。,

https://scattercode.co.uk/2016/01/05/multiple-databases-with-spring-boot-
和-spring-data-jpa/
https://scattercode.co.uk/2013/11/18/spring-data-multiple-databases/
https://medium.com/@joeclever/using-multiple-datasources-with-spring-boot-and-spring-data-6430b00c02e7

但我的用例是实体 foo 和 bar 存在于多个模式中,我想使用单个实体和存储库来访问所有模式。数据不会在所有模式中复制。它在它们之间进行划分。

因此,如果我需要搜索用户 John Doe,我必须通过 Schema 1 和
如果我找不到他,请转到下一个模式。

我已经尝试了上述所有教程(即使它们不符合我的
用例),希望我能破解它,让它像一个
概念证明。
我也研究过 AbstractRoutingDataSource
( http://fizzylogic.nl/2016/01/24/make-your-spring-boot-application-multi-tenant-aware-in-2-steps/ , http://kimrudolph.de/blog/spring-datasource-routing )
和 MultiTentancy 但这两者都谈到可以访问单个
任何时间点的模式。
我只需要一些指导或链接来遵循并完成这项工作。

提前致谢。

最佳答案

你需要看AbstractRoutingDataSource并使用它。

So if I need to search for User John Doe I have to go through Schema 1 and if I don't find him, move onto the next schema.



因此,您需要在第一个模式中搜索,如果未找到,则继续下一个模式。

在上面链接中给出的那个例子中,
 CustomerContextHolder.setCustomerType(CustomerType.GOLD);
 List<Item> items = catalog.getItems();
 if(isEmpty(goldItems)){
  CustomerContextHolder.setCustomerType(CustomerType.SILVER);
  items = catalog.getItems();  
 }

更多详情请见in another qn here

关于spring - 具有相同实体和存储库的多个数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48674412/

相关文章:

java - 在 jpa CRUD 存储库中保存并更新

hibernate - Spring 数据问题 - org.hibernate.HibernateException : identifier of an instance of {Entity} was altered from 1 to 2

java - 如何在 spring/hibernate/jpa 中自动创建表?

java - Hibernate repo查询访问mongodb嵌入文档

java - 表达出未满足的依赖

java - 将 Spring 与 JavaFX Service 类集成会导致 Service 失败

java - 将 Spring Boot JAR 应用程序转换为 WAR

java - Spring-Data-JPA - 查询返回 null - EmbeddedId

java - 有没有办法配置 ehcache 在无法获取更新版本时返回过期对象?

java - 使用 Spring Security @configuration 的同一应用程序中的两个领域