springAPI对事物支持之注解式配置

一、无Spring核心配置文件:applicationContext.xml下开启注解式事物

@Configuration
@EnableTransactionManagement
public class Configuration {}

二、有Spring核心配置文件:applicationContext.xml下开启注解式事物

<!-- 开启spring对注解事务的支持-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

三、在业务层使用@Transactional注解

  @Service("accountService")
  @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
  public class AccountServiceImpl implements IAccountService {
           @Autowired
           private IAccountDao accountDao;
           @Override
           public Account findAccountById(Integer id) {
                    return accountDao.findAccountById(id);
           }
           @Override
           @Transactional(readOnly=false,propagation=Propagation.REQUIRED)
           public void transfer(String sourceName, String targeName, Float money) {
                    //1.根据名称查询两个账户
                    Account source = accountDao.findAccountByName(sourceName);
                    Account target = accountDao.findAccountByName(targeName);
                    //2.修改两个账户的金额
                    source.setMoney(source.getMoney()-money);//转出账户减钱
                    target.setMoney(target.getMoney()+money);//转入账户加钱
                    //3.更新两个账户
                    accountDao.updateAccount(source);
                    //int i=1/0;
                    accountDao.updateAccount(target);
posted @ 2020-08-03 23:09  jock_javaEE  阅读(80)  评论(0编辑  收藏  举报