Manan Shah
Manan Shah

Reputation: 1098

How to check whether session has already open transaction or not in hibernate?

My requirement is i want to perform a database operation. So, i am doing...

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

This works good when my session does not contain any previously uncommited/unrolledback tranasction.

Now, Problem Sceanario is here...

Sceanario:

there is one service... which called myFunction() and that service has already one active transaction in session.

Problem: When myfunction() executes tx.rollback()... it also rolled back parent's transaction.

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

I have tried...

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

but in the case

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.

My question is still same:

Is there nay way to determine... weather hibernate session contains any previous open/uncommited/active/unrolledback/continue transaction?

Upvotes: 5

Views: 9599

Answers (1)

Nicholas
Nicholas

Reputation: 16056

Can you use Session.isDirty() ?

Upvotes: 1

Related Questions