Spring + Hibernate + Quartz: dynamic work

I want to create dynamic jobs using Quartz, Spring and Hibernate. Users interact with the web service to create jobs of this class:

public class StartJobSpring extends QuartzJobBean {

    private String jobId;
    private String jobType;

    @Autowired
    private NoaJobInstancesDAO njiDAO;

    @Transactional
    @Override
    protected void executeInternal(JobExecutionContext context)
            throws JobExecutionException {

        JobKey key = context.getJobDetail().getKey();
        JobDataMap dataMap = context.getMergedJobDataMap();

        // some logic
        njiDAO.create(instanceUUID, noaJob.getNoaJob(jobId), jobType);
    }
}

      

NoaJobInstancesDAO is a simple DAO class that uses the Hibernate EntityManager :

@Repository
public class NoaJobInstancesDAOHibImpl implements NoaJobInstancesDAO {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    public NoaJobInstanceJPA create(NoaJobInstanceJPA entity) {
        entityManager.persist(entity);
        return entity;
    }

    @Override
    public void create(String instance_uuid, NoaJobJPA job, String job_type) {
        NoaJobInstanceJPA entity = new NoaJobInstanceJPA(instance_uuid, job,
                job_type, "CREATED", null, null, "", "N", "N");
        this.create(entity);
    } 
}

      

The problem is that when this job fires an exception is thrown:

javax.persistence.TransactionRequiredException: No transactional EntityManager available

      

and I can't figure out why! I plan to work this way in the Manager class

JobDetail job = newJob(StartJobSpring.class).withIdentity(//anId)
                .setJobData(//aJobMap).build();
getScheduler().getObject().scheduleJob(job, trigger);

      

where the scheduler is connected to the dispatcher as

@Autowired
private ApplicationContext applicationContext;

@Bean
SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource, JpaTransactionManager transactionManager) {

    SchedulerFactoryBean bean = new SchedulerFactoryBean();

    AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
    jobFactory.setApplicationContext(applicationContext);
    bean.setJobFactory(jobFactory);

    bean.setTransactionManager(transactionManager);

    return bean;
}

      

The AutowiringSpringBeanJobFactory class is the same as Autowiring .

There is something wrong in my suggestion in the scheduler explorer. Actually, I don't understand how I can get the application context.

EDIT1: The application context looks correct. The problem may not be there.

EDIT2: I am using one bean config (not xml files). Here's the main methods:

@Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource   dataSource) {
     LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
     entityManagerFactoryBean.setDataSource(dataSource);
     entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
     entityManagerFactoryBean.setPackagesToScan("package");

    Properties jpaProperties = new Properties();
    jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.OracleDialect");
    jpaProperties.put("hibernate.show_sql", "false");
    jpaProperties.put("hibernate.hbm2ddl.auto", "update");

    entityManagerFactoryBean.setJpaProperties(jpaProperties);

    return entityManagerFactoryBean;
}

@Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(entityManagerFactory);
    return transactionManager;
}

@Bean
public NoaJobInstancesDAO noaJobInstancesDAO() {
    NoaJobInstancesDAOHibImpl noaJobInstancesDAO = new NoaJobInstancesDAOHibImpl();
    return noaJobInstancesDAO;
}

      

+3


source to share


3 answers


SHORT SOLUTION: Let Spring do your jobs through factories.

LONG DISSOLVE: Long description here. I changed my config file by importing the xml config file:

<bean name="complexJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
    <property name="jobClass" value="jobs.StartJob" />
    <property name="durability" value="true" />
</bean>

<bean id="cronTrigger"
        class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
    <property name="jobDetail" ref="complexJobDetail" />
    <property name="cronExpression" value="0/5 * * ? * SAT-SUN" />
</bean>

      

This way you have a Spring factory that instantiates jobs. Now, here's the updated java config class

@ImportResource({"spring-quartz-context.xml"})
public class BeanConfig {
    //autowired from xml
    @Autowired JobDetailFactoryBean jobDetailFactory;
    @Autowired CronTriggerFactoryBean cronTriggerFactory;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(LocalContainerEntityManagerFactoryBean entityManagerFactory) {

        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setApplicationContextSchedulerContextKey("applicationContext");

        bean.setSchedulerName("MyScheduler");

        //used for the wiring
        Map<String, Object> schedulerContextAsMap = new HashMap<String, Object>();
        schedulerContextAsMap.put("noaJobDAO", noaJobDAO());
        schedulerContextAsMap.put("noaJobInstancesDAO", noaJobInstancesDAO());
        schedulerContextAsMap.put("esbClient", this.esbClient());
        bean.setSchedulerContextAsMap(schedulerContextAsMap);

        bean.setQuartzProperties(quartzProperties());

        return bean;
    }

    @Bean
    public Properties quartzProperties() {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("quartz.properties"));
        Properties properties = null;
        try {
            propertiesFactoryBean.afterPropertiesSet();
            properties = propertiesFactoryBean.getObject();

        } catch (IOException e) {
            log.warn("Cannot load quartz.properties.");
        }

        return properties;
    }

    // other beans (as included in the question)
}

      



I am using bean for scheduling jobs. So I inject factories into this bean first. Then when I want to schedule a task, I use this snippet

JobDetail job = jobDetailFactory.getObject();
Trigger trigger = cronTriggerFactory.getObject();
scheduler.schedule(job, trigger);

      

I also changed the work class

@Service
public class StartJob extends QuartzJobBean {

    // the DAO
    private NoaJobInstancesDAO njiDAO;

    public void executeInternal(JobExecutionContext context)
            throws JobExecutionException {
        init(context.getJobDetail().getJobDataMap(), context.getScheduler()
                    .getContext());
        // some logic here
        njiDAO.create(params);
    }

    private void init(JobDataMap jobContextMap,
            SchedulerContext schedulerContext) {
        // some initialization using the job data map, not interesting for DAOs

        // row that inject the correct DAO
        this.njiDAO = (NoaJobInstancesDAO) schedulerContext
                .get("noaJobInstancesDAO");
    }
}

      

Problem solved!

0


source


you are in a spring managed context and you are trying to access the EntityManager with @PersistentContext which is the javax.persistence annotation. Try the autwiring EntityManagerFactory bean with @Autowire, which I believe configured it in spring-context.xml and used entityManagerFactory.createEntityManager () to provide you with a spring managed entity manager that will be wrapped by spring and in the transaction manager you define



0


source


I solved this problem:

In the assignment (required to get the interface):

public class SchedulerJob extends QuartzJobBean {
public void executeInternal(JobExecutionContext context)
        throws JobExecutionException {
    try{
        <YOUR_BEAN_DAO_INTERFACE_OBJECT> = ((ApplicationContext) context.getJobDetail().getJobDataMap().get("applicationContext")).get("<YOUR_BEAN_DAO_INTERFACE_ID>");
    } catch (Exception e ){
        e.printStackTrace();
        return;
    }
}

      

}

In the context of the application .xml of the application: Also need to be declared in this xml as a bean:

<!-- Spring Quartz Scheduler job -->
<bean name="schedulerJob" class="org.springframework.scheduling.quartz.JobDetailBean">
    <property name="jobClass" value="<PATH_OF_YOUR_CLASS_JOB>.SchedulerJob" />
    <property name="applicationContextJobDataKey" value="applicationContext" />
</bean>

<!-- Cron Trigger, run every 10 seconds -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="jobDetail" ref="schedulerJob" />
    <property name="cronExpression" value="0/10 * * * * ?" />
</bean>

<!-- DI -->
<bean id="scheduler"
    class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="jobDetails">
        <list>
            <ref bean="schedulerJob" />
        </list>
    </property>

    <property name="triggers">
        <list>
            <ref bean="cronTrigger" />
        </list>
    </property>
</bean>

      

0


source







All Articles