如何在休眠时检查会话是否已经打开了事务?

时间:2013-07-17 07:17:45

标签: hibernate session transactions struts

我的要求是我想执行数据库操作。 所以,我在做......

Public boolean myFunction(){
    Session session = sessionFactory.getCurrentSession();
    if(session!=null){
        if (tx != null) {
            Transaction tx = session.beginTransaction();
            //Perform database operation...
            tx.rollback();
            if (session.isOpen()) {
            session.close();
            }
            tx = null;
            session = null;
        }
    }else{
        return;
    }
}

当我的会话不包含任何先前未提及/未展开的回溯时,这种方法很有效。

现在,问题Sceanario就在这里......

Sceanario:

有一个服务...调用myFunction(),该服务在会话中已有一个活动事务。

问题: 当myfunction()执行tx.rollback()时...它还回滚了父事务。

1.) Why this happen???
2.) Is there nay way to determine... weather hibernate session contains any previous open/uncommited/active/unrolledback/continue transaction?

我试过......

Public boolean myFunction(){
    Session session = sessionFactory.getCurrentSession();
    if(session!=null){
        if (tx != null) {
            boolean isAlreadyTransactionStarted = sessionFactory.getCurrentSession().getTransaction().isActive();
            if(isAlreadyTransactionStarted){
                Transaction tx = sessionFactory.getCurrentSession().getTransaction();
            }else{
                Transaction tx = session.beginTransaction();
            }
            //Perform database operation...
            if(isAlreadyTransactionStarted){
                tx.rollback();
                if (session.isOpen()) {
                session.close();
                }
                tx = null;
                session = null;
            }else{
                //Nothing to do...
            }
        }
    }else{
        return;
    }
}

但是在案件中

1.) When parent call contains any active transactions then isAlreadyTransactionStarted becomes true.

2.) But in the case call which does not contains any transaction, also isAlreadyTransactionStarted becomes true.

我的问题仍然存在:

有没有办法确定...天气休眠会话包含任何以前的开放/未通信/活动/解压缩/继续交易?

1 个答案:

答案 0 :(得分:1)

你能使用Session.isDirty()吗?