我有这样的东西:
1)带有方法的DAO类,用于执行事务,例如使用java.sql.ConnectionwithdrawSum(int idAccount, float amount)
和putSum(int idAccount, float amount)
java.sql.PreparedStatement类对DB执行原子操作。
2) java.lang.reflect。InvocationHandler实现者,whick 用于在事务前获取连接和事务后提交/回滚:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Connection connection = null;
try{
connection = DaoUtil.INSTANCE.getConnection();
connection.setAutoCommit(false);
method.invoke(connection, args);
connection.commit();
} catch(InvocationTargetException ex){
connection.rollback();
} finally{
DaoUtil.INSTANCE.closeConnection(connection);
}
return null;
}
3)事务管理器,它创建代理实例并在其帮助下调用执行事务的方法,如下所示:
TransactionManager transManager = new TransactionManager();
InvocationHandler transHandler = new MyInvocationHandler(transManager);
TransactionManager proxy = (TransactionManager) Proxy.newProxyInstance(
transManager.getClass().getClassLoader(), transManager.getClass().getInterfaces(), transHandler);
proxy.transferMoney(withdrawAccountid, putAccountId, transactionSum);
......
public void transferMoney(int withdrawAccountid, int putAccountId, float transactionSum){
AccountDao.getInstance().withdrawSum(withdrawAccountid, transactionSum);
AccountDao.getInstance().putSum(putAccountId, transactionSum);
}
问题是:要在 DAO 方法中执行语句,我需要初始化Connection对象。它被初始化并传递给InvocationHandler的调用方法。它应该如何在 DAO 方法中正确初始化?有任何想法吗?提前致谢。