@Transactional(rollbackFor = Exception.class) 回滾事務。
@Service
@Transactional(rollbackFor = Exception.class)
public class UserService {
public void transfer(...) throws InsufficientBalanceException {
if (balance < amount) throw new InsufficientBalanceException("餘額不足");
// 更新資料庫...
}
}
@Controller
public class UserAction {
@Autowired UserService userService;
public String transfer() {
try {
userService.transfer(...);
return "success";
} catch (InsufficientBalanceException e) {
addActionError(e.getMessage());
return "input";
}
}
}
@ControllerAdvice + @ExceptionHandler 統一處理。rollbackFor 指定。