- pom.xml 声明事务注解扫描
<tx:jta-transaction-manager/>
- Service 层使用注解
@Transactional 默认 readOnly 属性默认是 false, 表示开始事务
注解修饰类,表示所有方法采用事务方式, 可以单独注解方法, 是否开启事务
@Transactional(readOnly = true)
@Component("accountService")
public class AccountServiceImpl implements AccountService {
@Resource
private AccountDao accountDao;
@Override
public void addAccount(AccountBean accountBean) {
accountDao.addAccount(accountBean);
}
@Override
public List<AccountBean> findAll() {
return accountDao.queryAll();
}
@Override
@Transactional //单独开启事务, 当出现异常时会进行回滚, 保证数据库的原子性和一致性
public void transfer(String fromUser, String toUser, double money) {
accountDao.update(fromUser, -money);
int u = 2/0;
accountDao.update(toUser, money);
}
}
- test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean.xml")
public class MyTest01 {
@Autowired
private AccountService accountService;
@Test
public void test02(){
accountService.transfer("小明","小李",100);
}
}
测试结果, 数据未发生变化
网友评论