}
static void close(Connection conn) {
if(conn!=null) {
try {
conn.close();
}
catch(SQLException e) {}
}
}
static void executeSQL(String sql) {
Connection conn = null;
Statement stmt = null;
try {
conn = getConnection();
boolean autoCommit = conn.getAutoCommit();
conn.setAutoCommit(true);
stmt = conn.createStatement();
stmt.execute(sql);
conn.setAutoCommit(autoCommit);
}
catch(SQLException e) {
log.warn("Execute failed: " + sql + "\nException: " + e.getMessage());
}
finally {
close(stmt);
close(conn);
}
}
public static Object createProxy(final Object target) {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
return new TransactionCallback() {
@Override
protected Object doInTransaction() throws Exception {
return method.invoke(target, args);
}
}.execute();
}
}
);
}
}
注意DatabaseFixture的createProxy()方法,它將一個普通的DAO對象包裝為在事務范圍內執行的代理對象,即對于一個普通的DAO對象的方法調用前后,自動地開啟事務并根據異常情況提交或回滾事務。
文章來源于領測軟件測試網 http://www.kjueaiud.com/