终于运用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;
}
转载于:https://blog.51cto.com/shuaigee/1136595