【问题标题】:Can JdbcTemplate Share a Common Transaction?JdbcTemplate 可以共享一个公共事务吗?
【发布时间】:2019-12-03 02:48:12
【问题描述】:

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

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

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

    @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:我尝试使用 Transactional 注释手动创建模板/数据源,但对我来说没有成功。

    SingleConnectionDataSource dataSource = new SingleConnectionDataSource();

    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl(url);
    dataSource.setUsername(user);
    dataSource.setPassword(password);

    NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

【问题讨论】:

  • 您需要在实际应用程序流程中更改表吗?为什么会实时更改多次?是测试吗?
  • 该示例是一个测试,但在实际用例中我确实需要上述内容。表中的数据需要在用户操作期间完全刷新。仍然可以搜索有问题的表,因此刷新需要在单个事务中进行

标签: java spring-boot jdbc jdbctemplate spring-transactions


【解决方案1】:

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

仅仅告诉您使用@Transactional 注释来注释您的类是不够的,请将@EnableTransactionManagement 添加到您的配置中

您应该只将@Transactional 注释应用于具有公共可见性的方法

另外,要使用相同的连接,您可以在上下文中将 datasorce 设置为 SingleConnectionDataSource

包装使用后未关闭的单个 JDBC 连接。

【讨论】:

  • 我尝试将 Transactional 注释添加到方法中并手动将 SingleConnectionDataSource 设置为 JDBC 模板,但遗憾的是无法使其正常工作。我的实现中可能缺少一些东西吗?我在编辑中发布了代码。
  • @GetOtterHere 问题可能是因为alter table 是将提交的 DDL 语句,请参见 stackoverflow.com/questions/730621/…仅告诉您使用 @Transactional 注释来注释您的类是不够的,将@EnableTransactionManagement 添加到您的配置中
  • 好吧,看来alter table 是这种情况下的问题。删除它可以解决我看到的问题并将所有内容保存在一个事务中。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-06-13
  • 2011-08-27
  • 1970-01-01
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多