query across two different database table in spring JPA

本秂侑毒 提交于 2020-02-08 05:33:47

问题


I have three tables. Table1 is in DB1 and both table2 and table3 is in DB2 as mentioned below:

Table1 in DB1: customerId, accountNumber

Table2 in DB2: customerId, accountNumber, id

Table3 in DB2: id, name, country

I want to get name and country from table3 based on customerId and accountNumber from table1. the tables are related as mentioned above. Tables are not having any mapping, just the columns are same.

I am using spring JPA and MySql.

Could anyone please help how to perform a join query on above 3 tables across database in spring JPA (in JPARepository class).

I want to have a join query like in repo class to run:

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;

回答1:


You can configure the multiple data source configuration using the link :

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

And then you can able to run your query as follows:

@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();


来源:https://stackoverflow.com/questions/44368186/query-across-two-different-database-table-in-spring-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!