Search code examples
postgresql-10hibernate

Hibernate does not close idle session


I cannot kill session in idle status on postgres 10 This caused a very big problem during some test and fill postgres connection pull. After close connection, the session is in idle state and wont close enter image description here

I have the same problem in local and in production database. I tried to resolve it in local enviroment (this is why i attached a local screenshot) but nothing works.

I set idle_in_transaction_session_timeout to 1s, but the session is in idle, non idle in transaction I set connection.pool_size on hibernate configuration to 2, but the connection are not part of the pool

How can i effectively destroy the idle session avoiding lock the database.

This is my hibernate configuation

    <property name="hibernate.enable_lazy_load_no_trans">true</property>
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="show_sql">false</property>
    <property name="format_sql">false</property>
    <property name="use_sql_comments">false</property>
    <property name="hibernate.generate_statistics">false</property>
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="current_session_context_class">thread</property>

this an example of open and close session

    public UserEntity getUserById(String id) {
    Session session = null;
    UserEntity user = null;
    try {
        session =  Connection.getInstance().openSession();
        String s = id.toLowerCase();
        user = session.get(UserEntity.class, s);
    } catch (Exception e) {
        Logging.log(e);
    } finally {
        session.close();
    }
    return user;
}

And this is the getIstance method

public static SessionFactory sessionFactory = null;

private static AppConfig appConfig =  (AppConfig) ContextLoader.getCurrentWebApplicationContext().getBean("app");

private Connection(){ }

public static SessionFactory getInstance() {
    try {
        if (sessionFactory == null) {
            sessionFactory = new Configuration().configure(appConfig.getDb().getFile()).buildSessionFactory();
        }
        return sessionFactory;
    }catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

DB version: postgresql 10.5 Hibernate version: 5.3.7 Tomcat version: 8.0.33

UPDATE - RESOLVED

<property name="hibernate.dbcp.maxIdle">4</property>

Solution

  • This option should be used

    <property name="hibernate.dbcp.maxIdle">4</property>