即使在关闭会话后,Hibernate 也会在 oracle db 中保持非活动会话

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

在我的休眠应用程序中,我编写了以下用于将 EmployeeRegistration 对象保存到 oracle 数据库中的代码。

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

关闭会话后,它会在 oracle 数据库中保留非活动会话。我已经使用 oracle 中的以下查询检查了非活动会话。

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

如何通过休眠终止所有非活动会话。谁能帮我解决这个问题。

确保您没有多次创建 sessionFactory

在您的 finally 代码中尝试以下操作:

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

每次获得会话时,都会根据需要创建一个新的数据库连接(即:事务已启动)。最好使用连接池来克服这种行为。

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.

我建议您在处理库创建者定义的 基本 问题之前使用连接池...

您注意到该用户在 Oracle 数据库中有多少非活动会话?

如果您看到一个,那么它可能与您使用数据库打开的 SQL 终端会话有关。

如果您看到它不止一个并且每次执行代码时计数都在增加,那么您没有正确释放连接。这可能是连接泄漏。

或者您确实在使用连接池,并且不活动的连接与其管理的连接有关。 Inactive 此处表示他们当前未执行操作。这并不意味着存在连接泄漏。发布您的配置将有助于阐明一些问题。 您可以通过生成堆栈跟踪或通过代码调试来验证您是否正在使用连接池。

此外,请确保没有其他应用程序正在使用相同的凭据访问数据库。