Reputation: 1742
I have a below problem and I am looking for solution in Spring - MVC and Hibernate only.
Problem Statement: There is UI which is having a text area and Submit button. In text area user can write a SQL query and after submitting, this SQL query has to be executed at multiple databases.
Note: Assume that multiple databases are already configured.
Please tell me the best approach for implementing it.
Upvotes: 0
Views: 241
Reputation: 251
I will assume that you have multiple datasources wired in you application context (?). If so and assuming that they have different qualifiers, you can inject them into another component, typically a service which is invoked from your controller or directly into your controller.
@Autowired
List<DataSource> datasources;
Should do the trick, alternatively through constructor injection. With the latter, you can create a JdbcTemplate per DataSource. Then you loop through the list and execute the same sql query on all datasources.
Upvotes: 1
Reputation: 544
You might consider 2 options:
AbstractRoutingDataSource
With this solution you are able to switch to the right database before executing queries. So you could write something like
// GOLD database
CustomerContextHolder.setCustomerType(CustomerType.GOLD);
List<Item> goldItems = catalog.getItems();
assertEquals(3, goldItems.size());
System.out.println("gold items: " + goldItems);
// SILVER database
CustomerContextHolder.setCustomerType(CustomerType.SILVER);
List<Item> silverItems = catalog.getItems();
assertEquals(2, silverItems.size());
System.out.println("silver items: " + silverItems);
// DEFAULT database
CustomerContextHolder.clearCustomerType();
List<Item> bronzeItems = catalog.getItems();
assertEquals(1, bronzeItems.size());
System.out.println("bronze items: " + bronzeItems);
Here are some docs:
https://spring.io/blog/2007/01/23/dynamic-datasource-routing/
http://fedulov.website/2015/10/14/dynamic-datasource-routing-with-spring/
This involve that you know in advance what Transaction Manager you will need for a specific Service.
Upvotes: 1