18

我使用以下声明性 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;
    }
}

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

4

2 回答 2

28

如果事务在范围内,您可以TransactionStatusTransactionAspectSupport.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
   }
}
于 2013-01-16T23:22:24.147 回答
5

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

log4j.logger.org.hibernate.transaction=DEBUG,R
log4j.logger.org.springframework.transaction=DEBUG,R
于 2013-03-04T10:58:25.040 回答