当外部事务失败时,如何使内部事务回滚

时间:2020-07-24 04:40:20

标签: spring spring-boot jpa spring-data-jpa transactions

我想创建一个名为createTransaction的方法,如果成功,它将提交事务,但是如果失败,则将所有事务回退到某个表中。另一方面,即使事务日志失败或成功,我也希望将事务日志保存到db中。

我尝试过此代码,但是当我尝试输入未保存在db中的customerId时,该事务应回滚该事务,产品和客户实体,但仍会在product表中提交该事务。有人可以解释一下发生了什么,并给我解决方案吗?

public String createTransactionWithLog(TR_Transaction transaction) {
    String message = "";
    try {
        
        boolean successTransaction = createTransaction(transaction);
        if(successTransaction == true) {
            message = "Transaksi sukses";
        }else {
            message = "Transaksi gagal";
        }
        
    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }finally {
        Activity_Log log = new Activity_Log(LocalDateTime.now(), "DoTransaction", message);
        activityLogRepository.save(log);
    }
    
    return message;
    
}

@Transactional
public boolean createTransaction(TR_Transaction transaction) {
    long productId = transaction.getProductId();
    long customerId = transaction.getCustomer().getCustomerId();
    
    MS_Product product = productRepository.getOne(productId);
    MS_Customer customer = customerRepository.getOne(customerId);
    
    if(product == null || customer == null) {
        return false;
    }else {
        transaction.setCustomer(customer);
        
        int newProductStock = product.getProductStock() - transaction.getQuantity();
        product.setProductStock(newProductStock);
        
        transaction.setProductPrice(newProductStock);
        
        customer.getTransactions().add(transaction);
        
        TR_Transaction savedTransaction = transactionRepository.save(transaction);
        MS_Customer updatedCustomer = customerRepository.save(customer);
        MS_Product updatedProduct = productRepository.save(product);
        
        return true;
    }
}

0 个答案:

没有答案