【问题标题】:JDBCTemplate multiple statements in Transaction - propagationTransaction中的JDBCTemplate多条语句-传播
【发布时间】:2014-05-13 19:54:21
【问题描述】:

我正在使用JDBCTemplate 在事务中进行插入 + 一些更新。 问题是我必须以编程方式设置主键,我从一个跟踪主键的表中读取它。

public void insert(final COrder cOrder) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        public void doInTransactionWithoutResult(TransactionStatus status) {
            Long cOrderId = insertOrder(cOrder);
            insertOrderLines(cOrder, cOrderId);
            insertCOrderTaxes(cOrder, cOrderId);
            updateMStorage(cOrder);
            insertMTransactions(cOrder);
        }
    });
}

public Long insertOrder(COrder o) {
    Long cOrderId = getNextId("C_ORDER");
    o.setcOrderId(cOrderId);
            ...
}
//the above insert methods here

最后是getNextId() 得到下一个id。

public synchronized Long getNextId(final String tableName) {
        final IdHolder idHolder = new IdHolder(-1l);
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            public void doInTransactionWithoutResult(TransactionStatus status) {
                Long nextId = jdbcTemplate.queryForObject("SELECT CURRENTNEXT FROM AD_SEQUENCE WHERE NAME=?",
                        new String[] { tableName }, Long.class);
                jdbcTemplate.update("UPDATE AD_SEQUENCE SET CURRENTNEXT = CURRENTNEXT + 1 WHERE NAME=?",
                        new Object[] { tableName });
                idHolder.setId(nextId);
            }
        });
        return idHolder.getId();
    }

基本上我希望所有这些插入/更新全部完成或不完成,但是无论外部事务如何,我都需要提交这个 getNextId()(因为要保留下一个主键)。

我的问题是,传播PROPAGATION_REQUIRES_NEW 是否适合在方法getNextId() 中运行的事务?

【问题讨论】:

    标签: spring transactions jdbctemplate spring-transactions


    【解决方案1】:

    是的。如果您使用PROPAGATION.REQUIRES_NEW,当前事务(如果有)将暂停并创建一个新事务。一旦该事务的执行完成,如果没有发生错误,它将被提交,并且外部事务将被恢复。无论接下来发生什么,内部事务都已提交并且现在是独立的。

    在你上面的代码中,确保你的transactionTemplate已经配置了正确的传播模式,即:

    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    

    【讨论】:

    • 感谢 Setphane 的确认。对于传播行为设置,我在 Spring 上下文中配置了两个 TransactionTemplates。对于内部 TransactionTemplate,我设置了属性 <property name="propagationBehavior" value="3"/> <!-- PROPAGATION_REQUIRES_NEW -->
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 2020-01-12
    • 2021-02-04
    • 1970-01-01
    相关资源
    最近更新 更多