JFinal 源码导读第八天(1) Db.tx 事物

1.接上面的事物介绍
/**
 * 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的源码,尽情期待

转载于:https://my.oschina.net/skyim/blog/141032

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值