使用 Spring 将数据源与事务一起使用
Using DataSource with Transaction using Spring
我正在作为遗留 j2ee 应用程序的一部分工作(没有 Spring 或 Hibernate 支持的普通应用程序)
该应用程序公开了以下方法:
public DataSource getConnectionDataSource();
DataSource 由产品正确启动到特定的数据库模式。
当我想查询数据库时,我创建了一个 jdbcTemplate 对象并像这样查询:
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("PRINT_LOCA",printerLocation);
DataSource printersSchemaDS = context.getCommonServices().getConnectionDataSource("printersSchema");
NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(printersSchemaDS);
String printerId = jdbcTemplate.queryForObject("select printerId from printers where printer_location=:PRINT_LOCA ",parameters,String.class);
我的问题是,当我只有 DataSource 对象时,如何在单个事务中执行多个更新 SQL 语句?
我看到 Spring 中有 TransactionTemplate,但是否可以单独使用 DataSource 对象对其进行初始化?
谢谢!
尝试从数据源获取单连接,然后使用普通手动jdbc事务:
try (Connection con = datasource.getConnection();) {
con.setAutoCommit(false);
// insert logic
con.commit();
} catch (SQLException e) {
// handle exception
con.rollback();
}
完整示例在这里:
https://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html
我正在作为遗留 j2ee 应用程序的一部分工作(没有 Spring 或 Hibernate 支持的普通应用程序)
该应用程序公开了以下方法:
public DataSource getConnectionDataSource();
DataSource 由产品正确启动到特定的数据库模式。
当我想查询数据库时,我创建了一个 jdbcTemplate 对象并像这样查询:
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("PRINT_LOCA",printerLocation);
DataSource printersSchemaDS = context.getCommonServices().getConnectionDataSource("printersSchema");
NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(printersSchemaDS);
String printerId = jdbcTemplate.queryForObject("select printerId from printers where printer_location=:PRINT_LOCA ",parameters,String.class);
我的问题是,当我只有 DataSource 对象时,如何在单个事务中执行多个更新 SQL 语句?
我看到 Spring 中有 TransactionTemplate,但是否可以单独使用 DataSource 对象对其进行初始化?
谢谢!
尝试从数据源获取单连接,然后使用普通手动jdbc事务:
try (Connection con = datasource.getConnection();) {
con.setAutoCommit(false);
// insert logic
con.commit();
} catch (SQLException e) {
// handle exception
con.rollback();
}
完整示例在这里: https://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html