mysql事务自动提交的问题

1:mysql的aut0commit配置默认是开启的,也就是没执行一条sql都会提交一次,就算显示的开启事务也会导致多条SQL不在一个事务中,
如果需要相关的SQL在同一个事务中执行,那么必须将autocommit设置为OFF,再显式开启事务。
2:如果使用spring的事务,那么不存在这个问题,spring的事务默认是关闭自动提交的,做法是判断连接池是否开启事务自动提交,如果连接池开启自动提交则设置自动提交为关闭,否则不做操作,因为某些jdbc驱动做设置自动提交关闭代价昂贵。

/**
     * This implementation sets the isolation level but ignores the timeout.
     */
    @Override
    protected void doBegin(Object transaction, TransactionDefinition definition) {
              .........省略某些代码
            // 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);
            }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容