gpt4 book ai didi

mysql - Spring JPA 中跨两个不同数据库表的查询

转载 作者:行者123 更新时间:2023-11-29 18:50:40 30 4
gpt4 key购买 nike

我有三张 table 。 Table1 在 DB1 中,table2 和 table3 在 DB2 中,如下所述:

DB1 中的表 1:customerId、accountNumber

DB2 中的表 2:customerId、accountNumber、id

DB2 中的表 3:id、名称、国家/地区

我想根据 table1 中的 customerId 和 accountNumber 从 table3 中获取名称和国家/地区。这些表是相关的,如上所述。表没有任何映射,只是列相同。

我正在使用 spring JPA 和 MySql。

任何人都可以帮助如何在 Spring JPA 中跨数据库对上述 3 个表执行联接查询(在 JPARepository 类中)。

我想要像在存储库类中一样运行连接查询:

select distinct d2t3.id from DB1.Table1 d1t1, DB2.Table2 d2t2, DB2.Table3 d2t3
where d1t1.customerid=d2t2.customerid
and d1t1.accountNumber=d2t2.accountNumber
and d2t2.id=d2t3.id;

最佳答案

您可以使用链接配置多个数据源配置:

https://medium.com/@joeclever/using-multiple-datasources-with-spring-boot-and-spring-data-6430b00c02e7

然后您就可以按如下方式运行查询:

@Query(value = "select distinct d2t3 from DB1.Table1 d1t1, DB2.Table2 d2t2, 
DB2.Table3 d2t3 where d1t1.customerid=d2t2.customerid and
d1t1.accountNumber=d2t2.accountNumber and d2t2.id=d2t3.id", nativeQuery = true)
List<Table3> retrieveByQuery();

关于mysql - Spring JPA 中跨两个不同数据库表的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44368186/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com