Question

I'm doing an insert + some updates inside a Transaction using JDBCTemplate. The thing is that I have to set primary key programmatically which I read from a table which keeps track of Primary keys.

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

and finally getNextId() which gets the next 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();
    }

Basically I want all these insertions/updates done all or none, but this getNextId() I need to commit regardless of the outer transaction(because of reserving the next primary key).

My question is, is propagation PROPAGATION_REQUIRES_NEW the right one for Transaction which runs in method getNextId()?

Was it helpful?

Solution

Yes. If you use PROPAGATION.REQUIRES_NEW the current transaction, if any, will be paused and a new one will be created. Once the execution of that transaction completes, it will be committed if no error occurs and the outer transaction will be resumed. Regardless of what happens next, the inner transaction is committed and is now independent.

In your code above, make sure that your transactionTemplate has been configured with the right propagation mode, that is:

transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top