如何从HibernateTransactionManager获取事务状态

时间:2015-06-19 09:37:53

标签: java spring hibernate transactions jta

我正在尝试将我的spring事务管理器从 JtaTransactionManager 升级到 HibernateTransactionManager 。在JTA TransactionManager中,我们有一个方法,它给出了当前事务的状态。根据我们正在做一些操作的状态。实施如下:

private void checkTransactionStatus(TransactionStatus status){
             if(status instanceof DefaultTransactionStatus) {
                DefaultTransactionStatus transactionStatus = (DefaultTransactionStatus) status;
                if(transactionStatus.getTransaction() instanceof JtaTransactionObject){
                    JtaTransactionObject txObject = (JtaTransactionObject) transactionStatus.getTransaction();
                    int jtaStatus;
                    try {
                        jtaStatus = txObject.getUserTransaction().getStatus();
                        if(jtaStatus==Status.STATUS_MARKED_ROLLBACK){
                            // logic heare
                        }
                    } catch (SystemException e) {}
                }
             }
           }

我想用HibernateTransactionManager特定代码替换此方法。我分析并发现,HibernateTransactionManager使用 HibernateTransactionObject 作为事务对象。但是,不幸的是,它是一个私人的内部阶级,我不能用它来获得地位。然后我尝试使用父类 JdbcTransactionObjectSupport 。但是,我不知道如何从这个父类对象获取状态。

private void checkTransactionStatus(TransactionStatus status){
         if(status instanceof DefaultTransactionStatus) {
            DefaultTransactionStatus transactionStatus = (DefaultTransactionStatus) status;
            if(transactionStatus.getTransaction() instanceof JdbcTransactionObjectSupport){
                JdbcTransactionObjectSupport txObject = (JdbcTransactionObjectSupport) transactionStatus.getTransaction();
                //how to get the current status ?
            }
         }
       }

2 个答案:

答案 0 :(得分:2)

Spring有一种接收回调的机制。您可以实现TransactionSynchronization界面(或更轻松地扩展TransactionSynchronizationAdapter)。您可能希望实现afterCompletion(int)方法并将逻辑放在那里。

public class MyTxCallback extends TransactionSynchronizationAdapter {

    public void afterCompletion(int status) {
        if (status==STATUS_ROLLED_BACK) {
            //logic here.
        }
    }

}

然后,您可以在启动事务时通过调用TransactionSynchronizationManager将其绑定到事务。现在,当事务完成时,将调用该方法,您可以执行逻辑(无论使用何种基础事务资源)。

答案 1 :(得分:1)

如果您使用HibernateTransactionManager,您可以从Hibernate会话中获取当前事务状态:

LocalStatus status = session.getTransaction().getLocalStatus();

并且LocalStatus具有以下状态:

public enum LocalStatus {
    /**
     * The local transaction has not yet been begun
     */
    NOT_ACTIVE,
    /**
     * The local transaction has been begun, but not yet completed.
     */
    ACTIVE,
    /**
     * The local transaction has been competed successfully.
     */
    COMMITTED,
    /**
     * The local transaction has been rolled back.
     */
    ROLLED_BACK,
    /**
     * The local transaction attempted to commit, but failed.
     */
    FAILED_COMMIT
}