spring - 在声明式事务管理中,无论事务是提交还是回滚,如何在 Spring 中获取事务信息?

标签 spring hibernate transactions

我使用以下声明性 Spring 事务:

<!-- Declare a transaction manager-->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" />  
<!-- enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="transactionManager" mode="proxy" proxy-target-class="true"/>

这是 DAO:

@Repository
@Transactional(readOnly = true, propagation=Propagation.REQUIRES_NEW )
@Scope("prototype")
public class Xdao{

    public Object getValues(){
        .....
    }
}


@Service
@Scope("prototype")
public class Xservice{
private Xdao xdao;

    public Object getx(){
        xdao.getValues();//here I want to know whether the transaction started  is             
        //committed or rollback by aop. Is it possible somehow? I don't want to include that code 
        //in any service or dao layer. 
        .........
    }

    @Autowired
    public void setXdao(Xdao xdao){
        this.xdao=xdao;
    }
}

我想了解事务状态,即事务已提交或回滚。我需要它来记录日志。

最佳答案

如果事务在范围内,您可以从 TransactionAspectSupport.currentTransactionStatus() 获取 TransactionStatus。例如:

if (TransactionSynchronizationManager.isActualTransactionActive()) {
   TransactionStatus status = TransactionAspectSupport.currentTransactionStatus();
   ...
}

但是交易完成后这将不起作用。

您可以添加 TransactionSynchronization 并实现 afterCompletion(int status) 以记录状态或将其存储在 ThreadLocal 变量中以供以后使用.

public class LogTransactionSynchronization extends TransactionSynchronizationAdapter {
   @Override
   public afterCompletion(int status) {
      // log the status or store it for later usage
   }
}

关于spring - 在声明式事务管理中,无论事务是提交还是回滚,如何在 Spring 中获取事务信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13395794/

相关文章:

java - 如何加入 hibernate ?

spring - swagger springfox - bean 验证 JSR 303 无法识别

java - Spring 4 hibernate 4 JPA LazyInitializationException : failed to lazily initialize a collection of role

java - 每个子类都有表的 Hibernate 鉴别器列

java - 非法尝试将集合与两个打开的 session 相关联

mysql - 为什么在未发出提交时插入记录?

java - Hibernate 的 Session.close() 是否自动回滚未提交的事务?

java - 使用 Jackson 的过滤器将树结构序列化为 JSON

java - spring aop执行返回类型

Spring Boot + Spring-Loaded(IntelliJ、Gradle)