您当前的位置: 首页 > 

梁云亮

暂无认证

  • 2浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

利用动态代理实现事务统一管理 一

梁云亮 发布时间:2022-04-21 00:03:46 ,浏览量:2

DAO层
  • 接口
public interface DeptDao{
	int insert(Connection conn,Dept dept);
}
public interface EmpDao{
	int insert(Connection conn,Emp emp);
}
  • 实现类
public class DeptDaoImpl implements DeptDao{
	@Override
	public int insert(Connection conn,Dept dept){
		// ....... 具体操作数据库实现插入数据到数据库表的操作
	}
}
public class EmpDaoImpl implements EmpDao{
	@Override
	public int insert(Connection conn,Emp emp){
		// ....... 具体操作数据库实现插入数据到数据库表的操作
	}
}
Service层
  • 接口
public interface EmpService{
	/**
	  * 同时添加员工,以及该员工所在的部门
	  */
	int insert(Connection conn,Emp emp,Dept dept);
}
  • 实现类
public class EmpServiceImpl{
	private DeptDao dpetDao = new DeptDaoImpl();
	private EmpDao empDao = new EmpDaoImpl();
	/**
	  * 同时添加员工,以及该员工所在的部门
	  */
	int insert(Connection conn,Emp emp,Dept dept){
		deptDao.insert(conn,dept);
		System.out.println(3/0);
		empDao.insert(conn,emp);
	}
}
动态代理事务增强
public class TransactionProxy implements InvocationHandler {
    private Object target;

    public TransactionProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object res = null;
        if(args[0] instanceof  Connection) {
            Connection conn = (Connection) args[0];
            try{
                conn.setAutoCommit(false);
                res = method.invoke(target,args); //userService.add(User);
                conn.commit();
            }catch (Exception e){
                e.printStackTrace();
                conn.rollback();
            }finally {
                conn.setAutoCommit(true);
                conn.close();
            }
        }
        return res;
    }

    public Object getProxy(){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
    }
}
测试代码
public static void main(String[] args) throws SQLException {
	Dept dept = new Dept(20,"ACCOUNTING","NEWYORK");
	Emp emp = new Emp(7369, "SMITH", "CLERK", 7902,LocalDate.of(1980, 12, 17), 800D, null, 20);
	EmpService empService = EmpServiceImpl();
    TransactionProxy transactionProxy = new TransactionProxy(empService);
    EmpService proxy = (EmpService) transactionProxy.getProxy();

    boolean addRes = proxy.add(JdbcUtil.getConnection(),emp,dept);
    System.out.println(addRes);
}
存在问题

采用本博客的方式实现事务统一管理存在一个很大的问题,就是需要在Dao层的不同方法之间反复传递Connection对象,代码看起来很怪异。最终解决方案,请参看博客:【精品】利用动态代理实现事务统一管理 二

关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0502s