In my Spring Boot Webapp I have a scheduler class with @EnableScheduling and @EnableAsync running at night by @Scheduled. The class is obtaining a session with:
Session session = entityManager.unwrap(Session.class);
which results in this exception:
org.hibernate.SessionException: Session is closed!
What is the correct way to obtain a session for scheduled tasks?
Here is the following code:
Session session = em.unwrap(Session.class);
Query query = session.createQuery("SELECT l FROM Lei l ORDER BY l.id");
query.setFetchSize(Integer.valueOf(1000));
query.setReadOnly(true);
query.setLockMode("a", LockMode.NONE);
// http://stackoverflow.com/questions/5067619/jpa-what-is-the-proper-pattern-for-iterating-over-large-result-sets
ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
while (results.next()) {
Lei lei = (Lei) results.get(0);
writer.writeLEI(lei);
}
results.close();
session.close();