日期:2014-05-20 浏览次数:21000 次
<!-- spring2.0的配置方式 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> <!-- 事务通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- <tx:method name="add*" propagation="REQUIRED" /> --> <tx:method name="mod*" propagation="REQUIRED" /> <tx:method name="*" read-only="true" rollback-for="Exception,RuntimeException,SQLException" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- Spring AOP config --> <aop:config proxy-target-class="true"> <!-- 切入点 --> <aop:pointcut id="servicesPointcut" expression="execution(* com.zyujie.service..*Impl.*(..))" /> <!-- <aop:pointcut id="daoPointcut" expression="execution(* com.zyujie.dao..*.*(..))" /> --> <!-- 运行拦截 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="servicesPointcut" /> <!-- <aop:advisor advice-ref="txAdvice" pointcut-ref="daoPointcut" /> --> </aop:config>
/* * 添加用户,为了测试是否开启事务。DAO层的方法 */ public int addUser(SysUser user) { logger.debug("开始执行添加用户的操作......"); Connection con = ConnectionFactory.getConnection(); String sql = "INSERT INTO USER_INFO VALUES (?,?,?,?,?,?,?,?,sysdate)"; int result = 0; PreparedStatement ps = null; try { // con.setAutoCommit(false); ps = con.prepareStatement(sql); for (int i = 0; i < 1000; i++) { String temps = i + "user"; if (i == 600) { temps = null; } ps.setString(1, temps); ps.setString(2, "test"); ps.setString(3, "99"); ps.setString(4, "测试地市"); ps.setString(5, "888"); ps.setString(6, "测试部门"); ps.setString(7, "888888"); ps.setString(8, "2"); // ps.setString(9, ""); result += ps.executeUpdate(); //有人说是这里本身就已经提交了,但是还是问问大家。 } // con.commit(); } catch (Exception e) { logger.debug("添加用户事务回滚了......"); // throw new RuntimeException("error"); // 抛出异常,测试回滚 throw new RuntimeException(); // 抛出异常,测试回滚 } finally { try { if (ps != null) { ps.close(); } if (con != null) { con.close(); } } catch (SQLException e) { // e.printStackTrace(); // throw new RuntimeException(); // 抛出异常,测试回滚 } } return result; }
/* * 添加用户,为了测试是否开启事务。Service层的接口实现类,方法 */ public int addUser(SysUser user) { return sysUserDAO.addUser(user); }