Search code examples
javaoraclehibernatesessionhibernate-mapping

Hibernate keeping inactive session in oracle db even after closing the session


In my hibernate application I have written below code for saving EmployeeRegistration object into oracle db.

public Integer submitDetails(EmployeeRegistration es)
{
    Session session = factory.openSession();
    Transaction tx = null;
    Integer employeeID = null;
    try
    {
        tx = session.beginTransaction();
        employeeID = (Integer)session.save(es);
        session.flush();
        tx.commit();
    }
    catch(HibernateException e)
    {
        if(tx != null)
        {
            tx.rollback();
        }
        e.printStackTrace();
    }
    finally
    {
        if(session.isOpen())    {
        session.close();
        }
    }
    return employeeID;
}

After closing session, it keeps inactive sessions in oracle db. I have checked the inactive session using the below query in oracle.

SQL> select USERNAME,COUNT(*) FROM V$SESSION WHERE STATUS='INACTIVE' GROUP BY USERNAME ;

How to kill all the inactive session through hibernate. Can anyone help me in resolving this issue.


Solution

  • make sure that you are not creating the sessionFactory several times.

    In your finally code try the following:

    if (session != null && session.isOpen()) {
        session.flush();
        session.close();
    }
    

    Every time you get a Session a new database connection is created if needed (es: transaction started). It is better to use a connection pool to overcome this behavior.

    Edit from the docs

    Hibernate's own connection pooling algorithm is however quite rudimentary. It is intended to help you get started and is not intended for use in a production system or even for performance testing.

    I would suggest you to use a connection pooling before dealing with issues from something defined rudimentary from the creators of the library...