Quartz, Spring & Hibernate/JPA

Establishing a hibernate session in a wicket application is done by means of the OpenSessionInViewFilter class, which binds a Hibernate Session to the thread for the entire processing of the request. You’ll find plenty of references by googling for Wicket and Hibernate.

If you need background jobs to be executed, Quartz is a fantastic library, providing scheduling with cron syntax. Quartz is trivial to integrate into your application (whether with Spring or without), but we had a hard time to figure out how to handle Hibernate sessions correctly. When you want to use one of your DAOs in a Quartz Job you are very likely to hit a “Session is closed!” exception from Hibernate. The reason for this is that the Quartz Job does not run within the context of the servlet, therefore nobody took care of establishing a Hibernate Session.

Below you’ll find a sample Quartz Job which shows how to set up the Hibernate session like OpenSessionInViewFilter does during a servlet request:

Below you’ll find the relevant sections from the corresponding applicationContext.xml file.

Thanks to Uwe Schäfer who helped us find this solution!

2 thoughts on “Quartz, Spring & Hibernate/JPA”

  1. Most real applications won’t want to start the scheduler until they’ve determined whether they are running on a development machine or a production environment, so its usually better to set the autoStartup property of the SchedulerFactoryBean to false in the applicationContext.xml file, and then in your application startup to start the scheduler explicitly like this:

    StdScheduler quartz = (StdScheduler) (getSpringApplicationContext().getBean(“quartzScheduler”));
    if (!developmentMode)
    quartz.start();

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.