你,你可以注入兩個數據源,並選擇你的方法裏面的數據源按照你的邏輯:
public class SomeDaoImpl implements SomeDao {
private final JdbcTemplate jdbcTemplateA;
private final JdbcTemplate jdbcTemplateB;
@Autowired
public SomeDaoImpl(JdbcTemplate jdbcTemplateA, JdbcTemplate jdbcTemplateB) {
// injecting both JdbcTemplate instances
this.jdbcTemplateA = jdbcTemplateA;
this.jdbcTemplateB = jdbcTemplateB;
}
public void businessLogicMethod(...) {
// choosing the actual template to be used according to your logic
JdbcTemplate jdbcTemplate = chooseTemplate(...);
// now using the template to execute a query
jdbcTemplate.execute(...);
}
}
另一種選擇是,以實例2種SomeDaoImpl
情況下,注入一個JdbcTemplate
到每個人,並選擇DAO實例在你的服務層。
但是這兩種解決方案都有一個缺陷:事務通常在服務層(例如使用攔截器)啓動,並且它不知道要將請求路由到另一個數據源;所以可能發生事務在一個數據源上啓動,但查詢在另一個數據源上執行。
因此,最明智的解決方案是上一級並實例化2個服務,在每個DAO中使用不同的JdbcTemplate
實例。當然,2名交易經理必須進行配置並仔細連線(例如,通過@Transactional("transactionManagerA")
)。有關此處的更多信息Spring - Is it possible to use multiple transaction managers in the same application?
爲什麼不在查詢中使用模式名稱,而不是在數據源中定義模式名稱? – Zico
瀏覽此鏈接。沒有確切的答案,但你可能會有一些想法。 http://zetcode.com/articles/springbootqualifier/ – Prasath