DataSource连接池的autocommit是否应该被设置为false

先看看下面代码的注释,在Spring DataSourceTransactionManager.java, function doBegin:


// Switch to manual commit if necessary. This is very expensive in some JDBC drivers,

// so we don't want to do it unnecessarily (for example if we've explicitly

// configured the connection pool to set it already).

        if (con.getAutoCommit()) {

            txObject.setMustRestoreAutoCommit(true);

            if (logger.isDebugEnabled()) {

                logger.debug("Switching JDBC Connection [" + con + "] to manual commit");

            }

            con.setAutoCommit(false);

        }      

在我当前的Java Web应用中,autocommit没有特别的设置,那么默认就是true。

所以每一次事务开始时,设置数据库连接autocommit为false;当事务退出的时候,又设置回true; 我理解这是一种标准做法。由Spring管理事务,所有的SQL都在@Transactional标记的代码块中执行,也就是手动提交。所有的数据库连接都从连接池中获取。目前访问量在每小时300万左右。


所以一个典型的流程就是这样:

  1. conn = dataSource.getConnection();

  2. conn.setAutoCommit(false);

  3. stmt = conn.createStatement();

  4. stmt.executeQuery(...);

  5. conn.commit()/conn.rollback();

  6. conn.setAutoCommit(true);

我的问题是,来回设置autocommit是否有必要?是否昂贵?能否直接在数据库连接池上设置autocommit=false,来保持连接始终为false,跳过上面的第2步和第6步?


12345678_0001
浏览 1162回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java