只有执行了endTransaction方法,事务操作才会真正提交到数据库。
来看源码:
/**
* End a transaction. See beginTransaction for notes about how to use this and when transactions
* are committed and rolled back.
*/
public void endTransaction() {
acquireReference();
try {
getThreadSession().endTransaction(null);
} finally {
releaseReference(); //做一些引用回收工作
}
}
public void endTransaction(CancellationSignal cancellationSignal) {
throwIfNoTransaction();
assert mConnection != null;
endTransactionUnchecked(cancellationSignal, false);
}
private void endTransactionUnchecked(CancellationSignal cancellationSignal, boolean yielding) {
if (cancellationSignal != null) {
cancellationSignal.throwIfCanceled();
}
final Transaction top = mTransactionStack;
boolean successful = (top.mMarkedSuccessful || yielding) && !top.mChildFailed;
//mMarkedSuccessful在setTransactionSuccessful时被标记为true
RuntimeException listenerException = null;
final SQLiteTransactionListener listener = top.mListener;
if (listener != null) { //默认的beginTransaction方法,listener是空,这里不再分析
try {
if (successful) {
listener.onCommit(); // might throw
} else {
listener.onRollback(); // might throw
}
} catch (RuntimeException ex) {
listenerException = ex;
successful = false;
}
}
mTransactionStack = top.mParent;
recycleTransaction(top);
if (mTransactionStack != null) {
if (!successful) {
mTransactionStack.mChildFailed = true;
}
} else {
try {
if (successful) { //如果mMarkedSuccessful被标记为true并且中途没有异常,则真正提交到数据库
mConnection.execute("COMMIT;", null, cancellationSignal); // might throw
} else { // 否则回滚
mConnection.execute("ROLLBACK;", null, cancellationSignal); // might throw
}
} finally {
releaseConnection(); // might throw
}
}
if (listenerException != null) {
throw listenerException;
}
}
网友评论