Quartz定时器中打开与关闭hibernateSession,这样对hibernate2级缓存进行了优化,在打开的session中可以维护lazy加载,这样提升了hibernate在Quartz中的使用效率。废话不多说了,上代码:
- package com.net263.boss.charge.action;
- import org.apache.log4j.Logger;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.quartz.JobExecutionContext;
- import org.quartz.JobExecutionException;
- import org.springframework.orm.hibernate3.SessionFactoryUtils;
- import org.springframework.orm.hibernate3.SessionHolder;
- import org.springframework.scheduling.quartz.QuartzJobBean;
- import org.springframework.transaction.support.TransactionSynchronizationManager;
- public abstract class TransactionalQuartzTask extends QuartzJobBean {
- private static Logger logger = Logger.getLogger(TransactionalQuartzTask.class);
- private SessionFactory sessionFactory;
- public SessionFactory getSessionFactory() {
- return sessionFactory;
- }
- public void setSessionFactory(SessionFactory sessionFactory) {
- this.sessionFactory = sessionFactory;
- }
- /**
- * Most of this method is copied from the HibernateInterceptor.
- */
- protected final void executeInternal(JobExecutionContext ctx)
- throws JobExecutionException {
- Session session = SessionFactoryUtils.getSession(sessionFactory, true);
- boolean existingTransaction = SessionFactoryUtils
- .isSessionTransactional(session, getSessionFactory());
- if (existingTransaction) {
- logger.info("Found thread-bound Session for TransactionalQuartzTask");
- } else {
- TransactionSynchronizationManager.bindResource(getSessionFactory(),
- new SessionHolder(session));
- }
- try {
- executeTransactional(ctx);
- } catch (HibernateException ex) {
- ex.printStackTrace();
- throw ex;
- } finally {
- if (existingTransaction) {
- logger.debug("Not closing pre-bound Hibernate Session after TransactionalQuartzTask");
- } else {
- TransactionSynchronizationManager
- .unbindResource(getSessionFactory());
- SessionFactoryUtils
- .releaseSession(session, getSessionFactory());
- }
- }
- }
- /**
- * Implementing classes, implement this method.
- */
- protected abstract void executeTransactional(JobExecutionContext ctx)
- throws JobExecutionException;
- }
所有Quartz类都继承TransactionalQuartzTask类实现executeTransactional虚方法。
转载于:https://blog.51cto.com/zhengqidaxia/1026929