/**
* IAtom support transaction of database.
* It can be invoked in Db.tx(IAtom atom) method.
* <br>
* Example:<br>
* Db.tx(new IAtom(){<br>
* public boolean run() throws SQLException {<br>
* int result1 = Db.update("update account set cash = cash - ? where id = ?", 100, 123);<br>
* int result2 = Db.update("update account set cash = cash + ? where id = ?", 100, 456);<br>
* return result1 == 1 && result2 == 1;<br>
* }});
*/
2.Db.tx他的原理呢,我这里详细介绍一下,其实非常简单
/**
* Execute transaction.
* @param transactionLevel the transaction level
* @param atom the atom operation
* @return true if transaction executing succeed otherwise false
*/
public static boolean tx(int transactionLevel, IAtom atom) {
Connection conn = DbKit.getThreadLocalConnection();
if (conn != null) { // Nested transaction support
try {
if (conn.getTransactionIsolation() < transactionLevel)
conn.setTransactionIsolation(transactionLevel);
boolean result = atom.run();
if (result)
return true;
throw new ActiveRecordException("Nested transaction is failure."); // important:can not return false
}
catch (SQLException e) {
throw new ActiveRecordException(e);
}
}
Boolean autoCommit = null;
try {
conn = DbKit.getDataSource().getConnection();
autoCommit = conn.getAutoCommit();
DbKit.setThreadLocalConnection(conn);
conn.setTransactionIsolation(transactionLevel);
conn.setAutoCommit(false);
boolean result = atom.run();
if (result)
conn.commit();
else
conn.rollback();
return result;
} catch (Exception e) {
if (conn != null)
try {conn.rollback();} catch (Exception e1) {e1.printStackTrace();}
return false; // throw new ActiveRecordException(e);
} finally {
try {
if (conn != null) {
if (autoCommit != null)
conn.setAutoCommit(autoCommit);
conn.close();
}
} catch (Exception e) {
e.printStackTrace(); // can not throw exception here, otherwise the more important exception in previous catch block can not be thrown
} finally {
DbKit.removeThreadLocalConnection(); // prevent memory leak
}
}
}
3.跟我上一篇博客基本上差不多,下面就是链接
http://my.oschina.net/skyim/blog/140867
boolean result = atom.run(); 这个地方就是调用我们
int result1 = Db.update("update account set cash = cash - ? where id = ?", 100, 123);
int result2 = Db.update("update account set cash = cash + ? where id = ?", 100, 456);
4.如果返回false就回滚,返回true就提交
下一阶段我会开始写扩展ext的源码,尽情期待