技术开发 频道

JAVA设计模式之事务处理

    首先,我们引入这个Transaction Context外部对象,它的代码其实很简单,如果不了解动态代理技术的请先阅读其他资料。

    import java.lang.reflect.Method;

    import java.lang.reflect.Proxy;

    import java.sql.Connection;

    import com.strutslet.demo.service.SystemException;

    public final class TransactionWrapper {

    /**

    * 装饰原始的业务代表对象,返回一个与业务代表对象有相同接口的代理对象

    */

    public static Object decorate(Object delegate) {

    return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),

    delegate.getClass().getInterfaces(), new XAWrapperHandler(

    delegate));

    }

    //动态代理技术

    static final class XAWrapperHandler implements InvocationHandler {

    private final Object delegate;

    XAWrapperHandler(Object delegate) {

    this.delegate = delegate;

    }

    //简单起见,包装业务代表对象所有的业务方法

    public Object invoke(Object proxy, Method method, Object[] args)

    throws Throwable {

    Object result = null;

    Connection con = ConnectionManager.getConnection();

    try {

    //开始一个事务

    con.setAutoCommit(false);

    //调用原始业务对象的业务方法

    result = method.invoke(delegate, args);

    con.commit();   //提交事务

    con.setAutoCommit(true);

    } catch (Throwable t) {

    //回滚

    con.rollback();

    con.setAutoCommit(true);

    throw new SystemException(t);

    }

    return result;

    }

    }

    }

0
相关文章