iT邦幫忙

2022 iThome 鐵人賽

DAY 17
0
Software Development

這些年,我們早該學會的Spring Framework系列 第 27

Day27 - Declarative transaction management (3)

  • 分享至 

  • xImage
  •  

Review

昨日我們講解了Spring如何設定Declarative transaction management並透過例子來了解有transaction management能達到的效果。

今日我們將介紹@Transactional當中能設定的屬性,讓我們更了解Declarative transaciton management

@Transactional

Spring的transaction management在遇到Checked Exception、Unchecked Exception時有不同的行為,

  • Unchecked Exception:發生異常default會rollback
  • Checked Exception:發生異常default不會rollback

demo Checked Exception不會rollback

@Service
public class AccountService {
    @Autowired
    private AccountDao accountDao;
    @Transactional
    public void transferMoney(String from, String to , Integer amount) throws FileNotFoundException {
        accountDao.addMoney(to,amount);
        accountDao.minusMoney(from,amount);
        FileInputStream  fs = new FileInputStream("C://not_exist.txt");
        System.out.println("轉帳完成:"+from+" to "+to+" 金額:"+amount);
    }
}
@Test
public void testDay27() throws FileNotFoundException {
    ApplicationContext ioc = new ClassPathXmlApplicationContext("bean27.xml");
    AccountService service = ioc.getBean(AccountService.class);
    service.transferMoney("1","2",100);
}

Result
https://ithelp.ithome.com.tw/upload/images/20221012/20128084fXpHfshaOW.jpg

noRollbackFor / noRollbackForClassName

可設定Unckecked Exception為rollback

 @Transactional(noRollbackFor = {ArithmeticException.class})
public void transferMoney(String from, String to , Integer amount) throws FileNotFoundException {
    //略
}

@Transactional(noRollbackForClassName = {"java.lang.ArithmeticException"}){
    //略
}

Result
https://ithelp.ithome.com.tw/upload/images/20221012/20128084ZU9b0RIU6v.jpg

rollbackFor / rollbackForClassName

可設定Ckecked Exception為rollback

 @Transactional(rollbackForClass = {"java.io.FileNotFoundException"})
 public void transferMoney(String from, String to , Integer amount) throws FileNotFoundException {
    //略
}
 @Transactional(rollbackForClassName = {"java.io.FileNotFoundException"})
 public void transferMoney(String from, String to , Integer amount) throws FileNotFoundException {
    //略
}

Result
https://ithelp.ithome.com.tw/upload/images/20221012/20128084HFqveZlvPj.jpg


上一篇
Day26 - Declarative transaction management (2)
下一篇
Day28 - Declarative transaction management (4)
系列文
這些年,我們早該學會的Spring Framework30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言