【问题标题】:Spring @Transational no rollback for jdbctemplate.update(PreparedStatementCreator, KeyHolder)Spring @Transational no rollback for jdbctemplate.update(PreparedStatementCreator, KeyHolder)
【发布时间】:2014-06-25 10:27:21
【问题描述】:

我是 Spring 框架的新手。我用spring.xml定义了datasouce和DataSourceTransactionManager,这样我就可以用jdbctemplate对象插入数据了。
现在我想将rollback 添加到交易中。
不幸的是,这个rollback 仅适用于JdbcTemplate.updata(String SQL),不适用于JdbcTemplate.updatePreparedStatementCreatorKeyholder),我曾经通过insert 获取生成的ID。

@Override
@Transactional("txManagerTest")
public SQLQueryObjectIF process(SQLQueryObjectIF queryObj) {

    KeyHolder keyHolder = new GeneratedKeyHolder();
    for (final String query : queryObj.getQueries()) {
        System.out.println(query);

        // Rollback works fine for the "update" below. 
        //jdbcTemplate.update(query);


        // Rollback doesn't work for the "update" below. Don't why...
        jdbcTemplate.update(new PreparedStatementCreator() {

            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                jdbcTemplate.getDataSource().getConnection().setAutoCommit(false);
                PreparedStatement ps = jdbcTemplate.getDataSource().getConnection().prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
                return ps;
            }
        }, keyHolder);


        //log.info(keyHolder.getKeys().toString());
    }

        //just for rollback test
    if (keyHolder.toString().length()>-1){
        throw new RuntimeException("Test Error");
    }
    return queryObj;
}  

【问题讨论】:

    标签: spring rollback jdbctemplate transactional


    【解决方案1】:

    该代码应该像这样使用(您需要使用作为参数给出的连接),否则使用您的代码,您将通过直接访问 DataSource 实例(如果 Spring 不知道)获得 Spring 不知道的连接不知道,出现异常不知道回滚):

    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
         PreparedStatement ps = con.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
         return ps;
    }
    

    【讨论】:

    • 太好了。这正是我想要的。太好了,非常感谢。~~
    猜你喜欢
    • 2018-01-17
    • 1970-01-01
    • 2013-07-20
    • 2021-10-21
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    相关资源
    最近更新 更多