【发布时间】:2012-07-25 18:32:24
【问题描述】:
首先,我不能使用声明性@Transactional 方法,因为应用程序有多个 JDBC 数据源,我不想对细节感到厌烦,但只要说 DAO 方法传递了正确的数据就足够了-source 来执行逻辑。所有 JDBC 数据源都具有相同的架构,它们是分开的,因为我要为 ERP 系统公开其余服务。
由于这个遗留系统,有很多我无法控制的长期锁定记录,所以我想要脏读。
使用 JDBC 我将执行以下操作:
private Customer getCustomer(DataSource ds, String id) {
Customer c = null;
PreparedStatement stmt = null;
Connection con = null;
try {
con = ds.getConnection();
con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
stmt = con.prepareStatement(SELECT_CUSTOMER);
stmt.setString(1, id);
ResultSet res = stmt.executeQuery();
c = buildCustomer(res);
} catch (SQLException ex) {
// log errors
} finally {
// Close resources
}
return c;
}
好吧,我知道有很多样板。所以我试用了JdbcTemplate,因为我使用的是spring。
使用 JdbcTemplate
private Customer getCustomer(JdbcTemplate t, String id) {
return t.queryForObject(SELECT_CUSTOMER, new CustomerRowMapper(), id);
}
好多了,但它仍然使用默认的事务隔离。我需要以某种方式改变这一点。所以我考虑使用TransactionTemplate。
private Customer getCustomer(final TransactionTemplate tt,
final JdbcTemplate t,
final String id) {
return tt.execute(new TransactionCallback<Customer>() {
@Override
public Customer doInTransaction(TransactionStatus ts) {
return t.queryForObject(SELECT_CUSTOMER, new CustomerRowMapper(), id);
}
});
}
但是这里如何设置事务隔离呢?我在回调或TransactionTemplate 的任何地方都找不到它来执行此操作。
我正在阅读 Spring in Action,第三版,其中解释了我所做的,尽管关于事务的章节继续使用带有注释的声明性事务,但如前所述,我不能将其用作我的 DAO 需要在运行时根据提供的参数(在我的例子中是国家代码)确定使用哪个数据源。
任何帮助将不胜感激。
【问题讨论】:
标签: java spring jdbc jdbctemplate spring-jdbc