SpringBoot + SpringMVC + Mybatis + Vue遇到的问题(三)

通过SpringBoot的事务注解@Transactional,实现事务

    @Transactional(rollbackFor = Exception.class)
    public String borrow(Integer book_id, Integer account_id){

        System.out.println("查看用户状态");
        Account account = accountRepository.findByIdForUpdate(account_id);
        if (account.getLeft_lend_number() <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "OutOfMaxRend";
        }

        List<LendList> byAccountIdRended = lendListRepository.findByAccountIdRended(account_id);
        for (int i = 0; i < byAccountIdRended.size(); i++) {
            if (byAccountIdRended.get(i).getBook_id().equals(book_id)){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "AlreadyRendedThisOne";
            }
        }

        System.out.println("开始借书");
        Book book = bookRepository.findByIdForUpdate(book_id);
        if (book.getLeft_number() <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "OutOfBookNumber";
        }

        System.out.println("用户可借书");
        accountRepository.borrowByAccountId(account_id);

        System.out.println("书本数量可借");
        bookRepository.bookBorrowedByBookId(book_id);

        java.sql.Date currentDate = new java.sql.Date(System.currentTimeMillis());

        LendList lendList = new LendList();
        lendList.setAccount_id(account_id);
        lendList.setBook_id(book_id);
        lendList.setLend_date(currentDate);
        System.out.println(lendList);

        lendListRepository.save(lendList);
        System.out.println("借书记录已保存");

        return "success";
    }

    @Transactional
    public String returnbook(Integer lend_id){

        LendList lendList = lendListRepository.findByLendIdForUpdate(lend_id);

        Integer book_id = lendList.getBook_id();
        Integer account_id = lendList.getAccount_id();

        Account account = accountRepository.findByIdForUpdate(account_id);
        Book book = bookRepository.findByIdForUpdate(book_id);

        accountRepository.returnByAccountId(account_id);
        bookRepository.bookReturnedByBookId(book_id);

        java.sql.Date currentDate = new java.sql.Date(System.currentTimeMillis());

        lendList.setBack_date(currentDate);
        lendListRepository.returnBook(lend_id,currentDate);

        return "success";

    }

默认碰到异常会回滚,也可以设置手动回滚

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

 

posted @ 2020-04-19 15:36  咕咕刘三刀  阅读(9)  评论(0编辑  收藏  举报