Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 808
Manan Shah Avatar asked Nov 12 '22 01:11

Manan Shah


1 Answers

Can you use Session.isDirty() ?

like image 99
Nicholas Avatar answered Nov 15 '22 07:11

Nicholas