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

时间:2012-11-15 10:41:06

标签: 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;
    }
}

我想知道事务状态,即事务已提交或回滚。我需要它来记录。

2 个答案:

答案 0 :(得分:21)

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

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
   }
}

答案 1 :(得分:4)

将以下内容添加到log4j.properties将启用事务状态记录,

log4j.logger.org.hibernate.transaction=DEBUG,R
log4j.logger.org.springframework.transaction=DEBUG,R