0

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();
ropo
  • 1,466
  • 2
  • 18
  • 29

2 Answers2

0

Here is a test service I just created ( I'm using spring boot 1.4 with all the default configuration ):

@Service
public class ScheduledService {
    @Autowired
    private EntityManager entityManager;

    @Async
    @Scheduled(fixedRate = 500L)
    @Transactional
    private void reportCurrentTime() {
        entityManager = entityManager.getEntityManagerFactory().createEntityManager();
        Session session = entityManager.unwrap(Session.class);

        System.out.println(session.hashCode());
    }
}

Then I can see the session hashcode in the console

1410300721
966623925
181180995
1606490891
1882727729
635804073
1259672020
484131582
Liping Huang
  • 4,378
  • 4
  • 29
  • 46
  • I can also display the hashCode, but then I exeute a query I get the exception above – ropo Sep 22 '16 at 12:46
  • Executing a query in your example works for me. Now I need to figure out why it does not work in my project – ropo Sep 22 '16 at 13:02
0

Found the problem. Stupid me! I closed the session

session.close();

ropo
  • 1,466
  • 2
  • 18
  • 29