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.
Code:
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.