@Transaction - 注解方式处理事务

本文介绍了一种使用自定义注解和动态代理实现Java事务管理的方法。通过创建Transaction注解和TxProxy代理类,可以在方法级别控制事务的开启和提交,简化了DAO层的事务处理过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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());
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值