终于运用ThreadLocal实现了Connection和Transaction的管理

终于运用ThreadLocal实现了Connection和Transaction的管理

http://www.cjsdn.net/post/print?bid=2&id=89152

测试用例(部分)通过


public void testBeginTransaction() throws TransactionException,SQLException {
Transaction tx = null;
try {
tx = ConnectionManager.beginTransaction();

assertEquals("aaa",findProduct16());

updateProduct16();
assertEquals("萝卜",findProduct16());

assertEquals("Alice Mutton",findProduct17());
updateProduct17();
//assertEquals("白菜",findProduct17());

tx.commit();
assertTrue(tx.wasCommitted());
/*
tx.commit();
assertTrue(tx.wasCommitted());
assertEquals("萝卜",findProduct16());
*/

/*
tx.rollback();
assertTrue(tx.wasRolledBack());
assertEquals("aaa",findProduct16());
assertEquals("Alice Mutton",findProduct17());
*/

} catch (TransactionException e) {
tx.rollback();
assertTrue(tx.wasRolledBack());
throw e;
} catch (SQLException e) {
tx.rollback();
assertTrue(tx.wasRolledBack());
//throw new TransactionException(e);
}

assertTrue(ConnectionManager.currentConnection().getAutoCommit());
}


更新了一下

dao.rar (780.49k)
2.Re:终于运用ThreadLocal实现了Connection和Transaction的管理 [Re: wes109] Copy to clipboard
Posted by: wes109
Posted on: 2004-04-23 13:13

主要的管理类


public class ConnectionManager {
private static final ThreadLocal connection = new ThreadLocal();
private static ConnectionFactory factory;
private static boolean initialized = false;
private static final Log log = LogFactory.getLog(ConnectionManager.class);

private ConnectionManager() {
super();
}

private synchronized static void initialize() {
try {
factory = new Configuration().configure().buildConnectionFactory();
} catch (ConfigureException e) {
log.fatal(e);
}
log.info("ConnectionManager initialize success");
initialized = true;
}

public static Connection currentConnection() throws SQLException {
if(!initialized) {
initialize();
}
Connection conn = (Connection)connection.get();
if(conn == null) {
conn = factory.openConnection();
connection.set(conn);
}
return conn;
}

public static void closeConnection() throws SQLException {
Connection conn = (Connection)connection.get();
connection.set(null);
if(conn != null) {
conn.close();
}
}

public static Transaction beginTransaction() throws TransactionException{
Connection conn = null;
try {
conn = currentConnection();
} catch (SQLException e) {
log.error("Can't get current connection with SQLException:",e);
throw new TransactionException("Begin tracsaction fail with SQLException:", e);
}

return new TransactionFactory().beginTransaction(conn);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值