支持事务的条件:
1, 数据库的引擎类型必须是INNODE
2, applicationContext.xml配置开启
<!-- 添加事务支持 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 开启事务注解 --> <tx:annotation-driven transaction-manager="txManager" />
3. 逻辑处理增加事务注解@Transactional
public class OrdersServiceImpl implements OrdersService{ @Autowired private OrdersDao ordersDao; @Transactional @Override public int addOrders(Orders orders, int leftMoney) { ordersDao.addOrders(orders); if(leftMoney >= 1000){ Orders orders1 = new Orders(); orders1.setUsername("xiaoli"); orders1.setMoney(1000); orders1.setType(2); //转入 ordersDao.addOrders(orders1); } else{ throw new RuntimeException("余额不足,正在滚回"); } return 0; } }
4, 以上实例中可见,有异常,必须抛出异常, 通过触发异常,触发回滚