Cannot commit when autoCommit is enabled exception occurs when the druid connection pool is used to connect to the postgre database. After the investigation, the result is a druid bug.

Problem Description

Some interfaces are abnormal, and some data interfaces are normal. An exception is thrown: Cannot commit when autoCommit is enabled. The specific exception is longer than this, but the main reason is related to the autocommit configuration of the database.

Problem environment

The springmvc project uses Ali's druid as the database connection pool

 

Investigation process

Through the source code, it is found that the DataSourceTransactionManager of the spring-tx transaction will execute the following code every time:

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

In other words, every time Spring gets a connection, it will set AutoCommit=false, but it is obviously not effective here. Why didn't it take effect? ​​Then the suspected target was transferred to the data source, and our data source uses Ali's druid connection pool, so it is suspected to be a druid bug, the following is equivalent to replace the druid connection pool.

Replace connection pool

After replacing the connection pool with HikariCP, HikariCP supports setting autoCommit=false. After testing again , no problem is found. It is determined that it is the problem of Ali's druid connection pool .

 

Solution

1. Configure the database property autocommit=false to solve

If you do not want to configure the database, then refer to the following method

2. Replace the connection pool, do not use Ali's druid connection pool

 

Guess you like

Origin blog.csdn.net/eguid/article/details/108636179