昨日我們講解了Spring如何設定Declarative transaction management並透過例子來了解有transaction management能達到的效果。
今日我們將介紹@Transactional當中能設定的屬性,讓我們更了解Declarative transaciton management
Spring的transaction management在遇到Checked Exception、Unchecked Exception時有不同的行為,
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
可設定Unckecked Exception為不rollback
@Transactional(noRollbackFor = {ArithmeticException.class})
public void transferMoney(String from, String to , Integer amount) throws FileNotFoundException {
//略
}
@Transactional(noRollbackForClassName = {"java.lang.ArithmeticException"}){
//略
}
Result
可設定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