天天看点

@Transaction - 注解方式处理事务

1.自定义注解类

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
public @interface Transaction {
}
           

2.动态代理类

public class TxProxy implements InvocationHandler {
	private Logger log = Logger.getLogger(TxProxy.class);
	private Object srcObject;
	private TxProxy(Object o) {
		this.srcObject = o;
	}
	@SuppressWarnings("unchecked")
	public static <T>T getProxy(Object src) {
		Object proxedObj = Proxy.newProxyInstance(
				TxProxy.class.getClassLoader(), src.getClass().getInterfaces(),
				new TxProxy(src));
		return (T)proxedObj;
	}
	@SuppressWarnings("unchecked")
	public static <T> T getProxy(Object src,Class<T> cls) {
		Object proxedObj = Proxy.newProxyInstance(
				TxProxy.class.getClassLoader(), src.getClass().getInterfaces(),
				new TxProxy(src));
		return (T)proxedObj;
	}
	@SuppressWarnings("unchecked")
	public static <T> T getProxy(Class<T> cls) {
		Object src=null;
		try {
			src = cls.newInstance();
		}catch(Exception e){
			e.printStackTrace();
		}
		Object proxedObj = Proxy.newProxyInstance(
				TxProxy.class.getClassLoader(), src.getClass().getInterfaces(),
				new TxProxy(src));
		return (T)proxedObj;
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		if (method.isAnnotationPresent(Transaction.class)) {
			Connection conn = null;
			Object returnValue = null;
			try {
				conn = DataSourceUtils.getConnection();
				log.info("开始事务。连接对象为:"+conn);
				conn.setAutoCommit(false);
				returnValue = method.invoke(srcObject, args);
				log.info("提交一个事务");
				conn.commit();
			} catch (Exception e) {
				log.info("事务出错回滚");
				conn.rollback();
				throw new RuntimeException(e.getMessage(), e);
			} finally {
				log.info("将Connection放回到池中");
				conn.setAutoCommit(true);
				conn.close();
				/**
				 * 为了保证不出错,必须要remove一下
				 */
				DataSourceUtils.remove();
			}
			return returnValue;
		} else {
			log.info("不存在此注解,不开事务。");
			return method.invoke(srcObject, args);
		}
	}
}
           

3.使用,

在servlet中使用代理

@Transaction - 注解方式处理事务

要在@Transaction

public interface IOrderService {
	@Transaction
	public void saveOrder(Order order);
	
}
           

上面一段代码的DAO层的实现类,也就是可以不用管事务的任何事了,干干净净

public void saveOrder(Order order) {
		//保存订单和订单明细
		String sql = "insert into orders(id,userid,consignee,paytype,amt,state,orderdate) " +
				"values(?,?,?,?,?,?,?)";
		QueryRunner run = new QueryRunner();
		run.update(getConnection(),sql, order.getId(),order.getUserid(),
				   order.getConsignee(),order.getPaytype(),order.getAmt(),
				   "0",order.getOrderdate());
		List<OrderLine> lines = order.getOrderLines();
		for(OrderLine ol:lines){
			sql = "insert into orderline(id,orderid,bookid,amt,price) values(?,?,?,?,?)";
			run.update(getConnection(), sql,ol.getId(),ol.getOrderid(),ol.getBookid(),ol.getAmt(),ol.getPrice());
		}
	}
           

继续阅读