动态代理-事物

本文介绍了一个用于数据库操作的代理类TransactionHandler,该类通过Java反射机制实现事务管理,支持add、delete和modify等方法。
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

public class TransactionHandler implements InvocationHandler {

private Object targetObject;

public Object createProxyObject(Object targetObject) {
this.targetObject = targetObject;
return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),
targetObject.getClass().getInterfaces(),
this);
}

public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Connection conn = null;
Object retValue = null;
try {
conn = ConnectionManager.getConnection();
if (method.getName().startsWith("add") ||
method.getName().startsWith("delete") ||
method.getName().startsWith("modify")) {
System.out.println("begin transaction");
//开启事务
conn.setAutoCommit(false);
}

//调用目标对象上的业务逻辑方法
retValue = method.invoke(this.targetObject, args);

if (!conn.getAutoCommit()) {
System.out.println("commit transaction");
//提交事务
conn.commit();
}
// }catch(AppException e) {
// if (!conn.getAutoCommit()) {
// System.out.println("rollback transaction");
// //回滚事务
// conn.rollback();
// }
// throw e;
}catch(Exception e) {
e.printStackTrace();
if (!conn.getAutoCommit()) {
System.out.println("rollback transaction");
//回滚事务
conn.rollback();
}
if (e instanceof InvocationTargetException) {
InvocationTargetException ite = (InvocationTargetException)e;
throw ite.getTargetException();
}
throw new AppException("操作错误!");
}finally {
conn.setAutoCommit(true);
ConnectionManager.closeConnection();
}
return retValue;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值