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);
}
}
网友评论