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);
}
}