简体   繁体   English

事务部分提交或回滚

[英]Transaction partially committing or rolling back

I am facing some issue with transactions configured in my code.我的代码中配置的事务遇到了一些问题。 Below is the code with transactions which writes data to DB.以下是将数据写入数据库的事务代码。

Writer.java 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 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();
    }

}

Here data is getting stored into table 1 properly but sometimes, table 2 is getting skipped.这里数据被正确地存储到表 1 中,但有时,表 2 被跳过。

I am not sure how this is happening as both the tables have been written within same transaction.我不确定这是如何发生的,因为这两个表都是在同一个事务中编写的。

Either transaction is partially committing the data or partially rolling back.任一事务正在部分提交数据或部分回滚。

I have doubt that in the SomeDAO class I am injecting JdbcTemplate object which is creating new connection instead of using existing connection of transaction.我怀疑在SomeDAO class 中我正在注入JdbcTemplate object,它正在创建新连接而不是使用现有的事务连接。

Can anyone please help me here?任何人都可以在这里帮助我吗?

Try binding a Transaction Manager bean having your jdbcTemplate inside @Transactional:尝试在 @Transactional 中绑定一个包含 jdbcTemplate的事务管理器 bean:

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

And then use this transaction manager in @Transactional("txnManager").然后在@Transactional("txnManager") 中使用这个事务管理器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM