'Why would hibernate not close its session after select query?
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | FelixD |