问题
In java reactor, r2dbc. I have two tables A, B. I also have repositories for them defined. How can i get data made up of A join B?
I only come up with the following approach: call databaseClient.select from A and consequently in a loop call select from B.
But i want more efficient and reactive way. How to do it?
回答1:
TL;DR: Using SQL.
Spring Data's DatabaseClient
is an improved and reactive variant for R2DBC of what JdbcTemplate
is for JDBC. It encapsulates various execution modes, resource management, and exception translation. Its fluent API select/insert/update/delete methods are suitable for simple and flat queries. Everything that goes beyond the provided API is subject to SQL usage.
That being said, the method you're looking for is DatabaseClient.execute(…)
:
DatabaseClient client = …;
client.execute("SELECT person.age, address.street FROM person INNER JOIN address ON person.address = address.id");
The exact same goes for repository @Query
methods.
Calling the database during result processing is a good way to lock up the entire result processing as results are fetched stream-wise. Issuing a query while not all results are fetched yet can exhaust the prefetch buffer of 128 or 256 items and cause your result stream to stuck. Additionally, you're creating an N+1 problem.
来源:https://stackoverflow.com/questions/60145595/how-to-join-tables-in-r2dbc