Reputation: 4591
I've setup a Spring Data project with two different datasources and am trying to invoke database-specific functions from a single @Controller
. I have two separate Entity Managers, Connection Properties and Transaction Managers for each datasource.
Below is my current @Controller
@RequestMapping(value = "/searchDB1", produces="application/json", method = RequestMethod.GET)
public List<Map<String, Object>> getList1() {
List<Map<String, Object>> list = this.jdbcTemplate.queryForList(
"select name, id from db1.Database1"
);
return list;
}
@RequestMapping(value = "/searchDB2", produces="application/json", method = RequestMethod.GET)
public void getList2() {
List<Map<String, Object>> list = this.jdbcTemplate.queryForList(
"select name, id from db2.Database2"
);
}
This will obviously fail as my jdbcTemplate is only wired to a single database at a time - what might be the best way for my controller to choose between databases depending on which method is called (Abstracting to Service Impl, etc.)
Upvotes: 0
Views: 381
Reputation: 3121
There is nothing stopping you from depending on two JdbcTemplate
. You have not shown the rest of the code but you could depend on two data sources and initialize the JdbcTemplate
when needed as it is an utility class more than a dependable resource.
The most simple way of passing the two data sources is to make it explicit.
<bean id="myBean" class="my.Controller">
<property name="dataSource1" ref="ds1"/>
<property name="dataSource2" ref="ds2"/>
</bean>
Nevertheless, you can also use @Qualifier
as shown in the documentation.
@Controller
public class Controller {
...
@Autowired
@Qualifier("ds1")
private DataSource dataSource1;
@Autowired
@Qualifier("ds2")
private DataSource dataSource2;
...
}
Upvotes: 3