Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PersistenceContext in a Quartz Job

We're using Spring 3.1, JPA (via Hibernate) and Quartz. Typically we interact with the DB via @PersistenceContext annotation on Service beans, and either SpringMVC controllers, or GraniteDS-managed service invocation.

I'm working on writing a Quartz job that needs to interact with the database. I've tried everything I can find to get this working. I tried passing in a Spring-managed component (annotated with @PersistenceContext and @Transactional) via the jobMap, the call to entityManager.persist(o) executes, but nothing happens in the database. I also tried similar to this answer, creating a factory class to call autowireBean() on the job object. I set up the job class like so:

public class CreateAlertJob implements Job {

    @PersistenceContext
    EntityManager entityManager;

    @Override
    @Transactional
    public void execute(JobExecutionContext context) throws JobExecutionException {

        SomeEntity entity = new SomeEntity();
        entityManager.persist(entity);
    }
}

Same result, the method executes but the database is unaltered. I found this blog post which references a GitHub project. There he is using JpaInterceptor to establish a Hibernate session, but this uses the DAO pattern and I'd like to stick with using @PersistenceContext.

Clearly there is something about the Quartz thread that is preventing this from working properly? I'm about out of ideas and considering making a web service call to a SpringMVC controller just to get this working.

like image 796
NTyler Avatar asked Aug 19 '13 20:08

NTyler


1 Answers

Since your CreateAlertJob is not created by Spring, @Transactional in it doesn't take effect.

You have the following options:

  • Delegate actual work to Spring bean and put @Transactional there
  • Use programmatic transaction management
  • Use AspectJ-based AOP implementation instead of Spring default implementation (but it would be overkill for such a simple problem)
like image 167
axtavt Avatar answered Nov 10 '22 03:11

axtavt