在使用Executor Service创建的线程中使用声明性事务

时间:2014-01-15 15:27:17

标签: java spring hibernate

我有一个带有注释@Controller的服务层类,在服务调用中,我在线程中生成,并且正在更新数据库中的内容。我在thread的方法中使用了@transaction注释。但我得到hibernate异常“没有找到会话”。我需要在Thread中添加任何注释吗?

  

org.hibernate.HibernateException:找不到当前线程的会话       在org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)       在org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:978)       在com.mediaiq.commons.persistence.BaseRepository.getCurrentSession(BaseRepository.java:30)       在com.mediaiq.cms.persistence.AgencyRepository.getById(AgencyRepository.java:20)       在com.mediaiq.mail.client.AgencyLookupReportByDayClient.emailAgencyLookupConfirmation(AgencyLookupReportByDayClient.java:84)       在com.mediaiq.mail.client.AgencyLookupReportByDayClient.sendemailreport(AgencyLookupReportByDayClient.java:67)       在com.mediaiq.mail.client.BaseMailClient.run(BaseMailClient.java:222)       at java.util.concurrent.Executors $ RunnableAdapter.call(Executors.java:471)       at java.util.concurrent.FutureTask $ Sync.innerRun(FutureTask.java:334)       at java.util.concurrent.FutureTask.run(FutureTask.java:166)       在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)       at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:615)       在java.lang.Thread.run(Thread.java:722)

@Repository
public class BaseMailClient implements Runnable {

    public BaseMailClient() {

    }

    public BaseMailClient(PlacementsRepository placementsRepository, SessionFactory sessionFactory, String sessionID) {
    this.placementsRepository = placementsRepository;
    this.sessionFactory = sessionFactory;
    this.sessionID = sessionID;
    }

    public BaseMailClient(AgencyRepository agencyRepository, SessionFactory sessionFactory, String sessionID) {

    this.agencyRepository = agencyRepository;
    this.sessionFactory = sessionFactory;
    this.sessionID = sessionID;
    }

    private String      sessionID        = null;

    @Autowired
    private SessionFactory  sessionFactory;


    @Autowired
    private PlacementsRepository  placementsRepository;
    @Autowired
    private AgencyRepository      agencyRepository;



    final static Logger    logger          =LoggerFactory.getLogger(BaseMailClient.class);



    @Override
    public void run()
    {

        sendemailreport();

    }

@Transactional
    public void sendemailreport()
    {
        checkSessionID();
        try {
        emailAgencyLookupConfirmation();
        emailAgencyLookup();
        }
        catch (IOException | FailedToCreateTempFile e) {
        logger.info("Failed To mail due to exception :" + e.getMessage());
        }
        catch (Throwable e) {
        logger.info("Failed To mail due to exception :" + e.getMessage());
        }
    }

}

服务类:

@Transactional
@Controller
@RequestMapping(URLEndPoints.EMAIL)
public class SendMailService {

    @Autowired
    PlacementsRepository       placementsRepository;
    @Autowired
    AgencyRepository       agencyRepository;
    /**
     * 
     */
    @Autowired
    private SessionFactory   sessionFactory;

    @Autowired
    private ThreadPoolTaskExecutor mailJobExecutor;

    final static Logger     logger = LoggerFactory.getLogger(SendMailService.class);
 @RequestMapping(method = RequestMethod.POST, value = URLEndPoints.EMAIL_AGENCY_LOOKUP_BY_DAY, produces = "application/json")
    @ResponseBody
    public String emailAgencyLookupByDay(ServletRequest request,@PathVariable("agencyID") Integer agencyID,
              @PathVariable("startDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date startDate,
              @PathVariable("endDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date endDate )
    {
        logger.debug("POST:SendEmail:AgencyLookup");
        String sessionId = getSessionIDFromCookie(request);
        BaseClient mailServiceClient = new BaseClient(getAgencyRepository(), getSessionFactory(), sessionId);
        logger.debug("Getting Executor Instance");
        mailJobExecutor.submit(mailServiceClient);
        logger.debug("Submitted to Executor");
        return "SUCCESS";
    }
}

2 个答案:

答案 0 :(得分:1)

这里有一些问题。

首先,您自己创建了BaseClient对象,因此Spring无法添加@Transactional行为。

BaseClient mailServiceClient = new BaseClient(getAgencyRepository(), getSessionFactory(), sessionId);

相反,你应该让Spring为你创建一个这种类型的bean。使用prototype范围。

其次,你需要仔细阅读这个entry in the Spring documentation about Spring's proxying mechanism.不幸的是,从同一个类中的非事务方法调用@Transactional方法时,你不能指望任何事务行为,这就是你在这里做的

@Override
public void run()
{
    sendemailreport();
}

@Transactional
public void sendemailreport()
{
sendemailreport引用上调用

this,这是对象本身,而不是代理。因此,它不会有任何交易行为。

Consider looking into the @Async annotation alongside asynchronous execution.

答案 1 :(得分:0)

在Spring外部创建的线程不会附加休眠会话。您需要手动将新的休眠会话附加到线程;

Session session = SessionFactoryUtils.openSession(sessionFactory);
try
{
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}
catch(Exception e)
{
    Logger.debug("Session already bound");
}

(您需要注入sessionFactory)。

确保在线程完成之前会话未绑定;

public static void closeSession(Session se)
{
    try
    {
        try
        {
            TransactionSynchronizationManager.unbindResource(sessionFactory);
        }
        finally
        {
            if (se != null && se.isOpen() && se.isConnected())
            {
                SessionFactoryUtils.closeSession(se);
            }
        }
    }
    catch (HibernateException e)
    {
        Logger.fatal("Could not close session", e);
    }
}