【问题标题】:Transaction partially committing or rolling back事务部分提交或回滚
【发布时间】:2019-09-30 13:07:21
【问题描述】:

我的代码中配置的事务存在一些问题。 下面是将数据写入数据库的事务代码。

Writer.java

class Writer {

    @Inject
    private SomeDAO someDAO;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void write(){
        this.batchWrite();

    }


    private void batchWrite () {

        try {
            someDAO.writeToTable1(true);
        } catch(Exception ex) {
            someDAO.writeToTable1(false);
        }

        someDAO.writeToTable2();

    }
}

SomeDAO.java

class SomeDAO {

    @Inject
    private JdbcTemplate JdbcTemplate;

    public void writeToTable1(boolean flag) {
        // Writes data to table 1 using jdbcTemplate
        jdbcTemplate.update();
    }


    pulic void writeToTable2() {
        // Writes data to table 2 using jdbcTemplate
        jdbcTemplate.update();
    }

}

这里的数据被正确存储到表 1 中,但有时,表 2 被跳过。

我不确定这是怎么发生的,因为这两个表都是在同一个事务中写入的。

事务要么部分提交数据,要么部分回滚。

我怀疑在 SomeDAO 类中我正在注入 JdbcTemplate 对象,该对象正在创建新连接而不是使用现有的事务连接。

谁能帮帮我?

【问题讨论】:

    标签: java transactions jdbctemplate spring-transactions


    【解决方案1】:

    尝试绑定一个事务管理器 bean,在 @Transactional 中包含您的 jdbcTemplate

        //Create a bean
        @Bean
        public PlatformTransactionManager txnManager() throws Exception {
            return new DataSourceTransactionManager(jdbcTemplate().getDataSource());
        }
    

    然后在@Transactional("txnManager") 中使用这个事务管理器。

    【讨论】:

    • @Guarav 已经完成了@Bean(name = "datastoreTransactionManager") public PlatformTransactionManager transactionManager( @Qualifier("datastoreEntityManagerFactory") EntityManagerFactory entityManagerFactory) { return new JpaTransactionManager(entityManagerFactory); }
    • 您是否使用相同的 entityManagerFactory 进行写入操作?
    猜你喜欢
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 2013-11-20
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多