Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Transactional and JDBC autoCommit

On my actual application, I have a DBCP connection pool which doesn't have JDBC autoCommit=false set. It seems to have the default autoCommit=true. This is probably a mistake but I'd like to understand the impact of changing this parameter.

I am using: - Spring with @Transactional annotation - Spring Batch with JDBC readers and writers, eventually custom tasklets using JdbcTemplate

I would like to know if Spring does set autoCommit=false on the current connection if it is in the context of a transaction handled by the TransactionManager. Does it override the default setting? Because it seems to me it makes sense to do so.

like image 766
Sebastien Lorber Avatar asked Apr 30 '13 13:04

Sebastien Lorber


People also ask

Does JDBC automatically commit a transaction?

By default, JDBC uses an operation mode called auto-commit. This means that every update to the database is immediately made permanent. Any situation where a logical unit of work requires more than one update to the database cannot be done safely in auto-commit mode.

Does Spring @transactional lock table?

"@Transactional" as itself on any isolation level doesn't enabling any locking. To achieve locking behaviour you should use "@Lock" annotation or use " for update" in your query.

Does @transactional commit?

In Spring Boot, when @Transactional annotation is used, Spring Boot implicitly creates a proxy that will be creating a connection to the database. A transaction will be started and commit after the code has been executed errorless. Otherwise, it will roll back the changes if an exception occurred.

How does Spring @transactional really work?

At a high level, Spring creates proxies for all the classes annotated with @Transactional, either on the class or on any of the methods. The proxy allows the framework to inject transactional logic before and after the running method, mainly for starting and committing the transaction.


1 Answers

PlatformTransactionManager is an interface, so I would not blanket say that all implementations set AutoCommit = false, however the most common implementation (DataSourceTransactionManager) does set AutoCommit = false. see code snippet below from the doBegin method:

if (con.getAutoCommit()) {
            txObject.setMustRestoreAutoCommit(true);
            if (logger.isDebugEnabled()) {
                logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
            }
            con.setAutoCommit(false);
        }
        txObject.getConnectionHolder().setTransactionActive(true);

Now as you stated, it makes perfect sense to do so or you would not have a rollback segment to activate a rollback on.

like image 173
fpmoles Avatar answered Sep 21 '22 01:09

fpmoles