防止spring中使用@transaction注解后某行代码不回滚

问题描述 投票:0回答:1

我在函数中使用了 @transaction 注释,当发生任何异常时,它会回滚所有内容。我有一行代码,可以更新任务是否失败或在该函数内部的数据库中传递。我不希望该操作回滚该怎么办?

@Transactional
public void performTransactionAndAddEntry() {
    
    try {

    /// my other task like writing in a file and creating a mail body and attachment etc


        // Calling the method to add an entry to the database
        addEntryToDatabase();
    } catch (Exception e) {
    
        e.printStackTrace();
    }
}
java spring spring-boot spring-data
1个回答
0
投票

如果您需要对事务状态进行更细粒度的控制,请考虑使用编程事务而不是声明性注释。您可以使用 Spring 的

TransactionTemplate
或直接与
PlatformTransactionManager
交互。这种方法允许您显式地操纵交易状态。

@Autowired
private TransactionTemplate transactionTemplate;

public void performTransactionAndAddEntry() {
    try {
        // Other tasks (e.g., writing to a file, creating a mail body)
        // ...

        // Add an entry to the database (without triggering rollback)
        transactionTemplate.execute(status -> {
            addEntryToDatabase();
            return null;
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.