JdbcTemplate可以共享一个公共事务吗?

时间:2019-07-24 21:32:56

标签: spring-boot jdbctemplate spring-transactions

因此,我最初发布了一个问题here,关于我在混合JDBC模板/ JPA时遇到的问题。

但是我现在想知道是否甚至可以在JDBC模板操作之间共享一个公共事务?

示例将在单独的事务中更新表“ test”。

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public void storeDataInSingleTransaction(List<Test> testEntries) {
        namedParameterJdbcTemplate.update("DELETE FROM test", new HashMap<>());
        namedParameterJdbcTemplate.update("alter table test auto_increment = 1", new HashMap<>());

        String insertTestSQL = "INSERT INTO test VALUES (:id, :name, :value)";
        SqlParameterSource[] testBatch = SqlParameterSourceUtils.createBatch(testEntries.toArray());
        namedParameterJdbcTemplate.batchUpdate(insertTestSQL, testBatch);
    }

1 个答案:

答案 0 :(得分:0)

通常在Spring中,当您从@Transactional方法中调用方法时,它应该作为单个连接执行

  

您应仅将@Transactional注释应用于具有公开可见性的方法

此外,要使用相同的连接,您可以在上下文中将数据源设置为SingleConnectionDataSource

  

包装单个JDBC连接,该连接在使用后不会关闭。

相关问题