首先在.xml中开启sprong对注解事务的支持
applicationContext.xml
<tx:annotation-driven transaction-manager="transactionManager"/>
然后再Service中加上注解
service
@Service
@Transactional(readOnly=true,propagation= Propagation.SUPPORTS)
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;/*** 转账* @param source* @param target* @param money*/@Override@Transactional(readOnly=false,propagation=Propagation.REQUIRED)public void updateUser(String source, String target, Float money) {userMapper.updateUserOfSub(source, money);int a = 6/0;userMapper.updateUserOfAdd(target, money);}
}
最后测试
测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")//加载配置文件
public class ServiceTest {@Autowiredprivate UserService userService;/*** 转账业务*/@Testpublic void testUpdate(){userService.updateUser("张三丰","宋远桥",1F);}
}
- 结果为事务回滚 Rolling back JDBC transaction