Setup: I have Spring core 5 application + hibernate core (5.4.9.Final), to access database I use single hibernate session factory initialized when spring loads and then I get SessionFactory instance by using spring's @Autowired in all my @org.springframework.stereotype.Repository classes.
When this code gets called by Spring Controller or REST controller, it works fine, but I need to check something periodically so I used java.util.Timer and java.util.TimerTask for that, however when this same code gets called from timer thread I get following error:
Why the session is closed when accesing it from Timer thread ? Spring already by default processes controller requests in many threads and there is not a problem with that.
Messy solution: I have been able to supress this error by doing following, but this is really messy (+ not even using try-with-resources), however I have not been able to find any solution nor reason why calling this from a timer completely breaks SessionFactory.
The code above works only when call "s = sf.getCurrentSession();" is made first that always throws HibernateException and after that sf.openSession() works for some strange reason. If I try to add finally block where I try to do s.close() it starts throwing the same error again. So the only messy solution is to never close the session apparently which is really bad.
I'd like to point out also that legacy Hibernate is not the ORM that I would recommend for modern code. For many years now, Hibernate has supported the Java Persistence Architecture (JPA), which is a JEE-standard ORM protocol, unlike legacy Hibernate, which was a non-standard proprietary solution.
JPA is a component of the Enterprise JavaBeans version 3 standard, and can be used both with EJBs and with non-EJB mechanisms such as in stand-alone apps and partial-stack webapps (for example, Tomcat and jetty), just like legacy Hibernate does.
JPA is supported as part of Spring Data's Spring JPA component.
It's relatively easy to convert most legacy Hibernate to JPA. The Hibernate team was a major contributor to the design of JPA.
Some people, when well-known sources tell them that fire will burn them, don't put their hands in the fire.
Some people, being skeptical, will put their hands in the fire, get burned, and learn not to put their hands in the fire.
And some people, believing that they know better than well-known sources, will claim it's a lie, put their hands in the fire, and continue to scream it's a lie even as their hands burn down to charred stumps.