Home > Back-end >  Why would hibernate not close its session after select query?
Why would hibernate not close its session after select query?

Time:05-17

When calling the following method 10 times there are 11 open sessions on the database:

public void readHsql() {
        SessionFactory sessionFactory = getSessionFactory();
        if (sessionFactory != null) {
            try (Session session = sessionFactory.openSession()) {
                String queryString = "select r from Role r where r.name='test'";
                Query<Role> query = session.createQuery(queryString, Role.class);
                List<Role> list = query.getResultList();
            } catch (Exception e) {
                System.err.println("Error");
            }
        } else {
            System.err.println("Error");
        }
    }

On each iteration of the calling loop there is one more session. When stopping the java application the sessions are gone again. Why does a session not close when leaving the try-catch-block, I thought this should be done by Autoclosable? Also calling .close() or .disconnect() does not seem to change anything.

Is there anything to configure or any annotation to avoid this using hibernate 5.4.12.Final?

CodePudding user response:

Since getSessionFactory() is the only part not under control of hibernate I checked this one and found out that my implementation was not thread safe and under some circumstances returned multiple session factory instances for the same target which resulted in a growing number of sessions.

  • Related