How do I get transaction info in Spring whether transaction is committed or rollback in a declarative transaction management?

穿精又带淫゛_ 提交于 2020-05-26 10:48:09

问题


I use following declarative Spring transaction:

<!-- 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"/>

Here is the 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;
    }
}

I want to know about transaction status i.e transaction is committed or rolled back. I need it for logging.


回答1:


If transaction is in scope you can get TransactionStatus from TransactionAspectSupport.currentTransactionStatus(). For example:

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

But this will not work after transaction is completed.

You could add a TransactionSynchronization and implement afterCompletion(int status) to log the status or store it in a ThreadLocal variable for later usage.

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



回答2:


Adding the following to your log4j.properties will enable transaction status logging,

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


来源:https://stackoverflow.com/questions/13395794/how-do-i-get-transaction-info-in-spring-whether-transaction-is-committed-or-roll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!