transaction的实现中,首先,java的Connection是支持事务的,添加以下方法:
/** * 开启事务 */ public static void beginTransaction(){ Connection conn = getConnection(); if(conn !=null){ try { conn.setAutoCommit(false); } catch (SQLException e) { log.error(e.getMessage()); e.printStackTrace(); }finally { CONNECTION_HOLDER.set(conn); } } } public static void commitTransaction(){ Connection conn = getConnection(); if(conn !=null){ try { conn.commit(); conn.close(); } catch (SQLException e) { log.error(e.getMessage()); e.printStackTrace(); }finally { CONNECTION_HOLDER.remove(); } } } public static void rollbackTransaction(){ Connection conn = getConnection(); if(conn!=null){ try { conn.rollback(); conn.close(); } catch (SQLException e) { log.error(e.getMessage()); e.printStackTrace(); }finally { CONNECTION_HOLDER.remove(); } } }
包含了开启事务,提交事务,事务回滚的方法。
利用aop来实现transaction代理
Method method = proxyChain.getTargetMethod();
获取要代理的方法
method.isAnnotationPresent(Transaction.class)
检测上面是否加上了transaction注解
DatabaseHelper.beginTransaction(); result = proxyChain.doProxyChain(); DatabaseHelper.commitTransaction();
开启事务,提交事务
catch(Exception e){ log.error(e.getMessage()); DatabaseHelper.rollbackTransaction(); throw e; }
发生错误的时候,回滚数据。