Hibernate会话线程 [英] Hibernate Session Threading

查看:165
本文介绍了Hibernate会话线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题关于Hibernate和延迟加载。

I have a problem regarding Hibernate and lazy loading.

背景:
我有一个Spring MVC的Web应用程序,我用Hibernate为我的持久层。我使用的OpenSessionInViewFilter,使我能够在我的视图层延迟加载实体。而我扩展的HibernateDaoSupport类和使用的HibernateTemplate保存/加载的对象。一切都已经合作得非常好。直到现在。

Background: I have a Spring MVC web app, I use Hibernate for my persistence layer. I'm using OpenSessionInViewFilter to enable me to lazy load entities in my view layer. And I'm extending the HibernateDaoSupport classes and using HibernateTemplate to save/load objects. Everything has been working quite well. Up until now.

问题:
我有一个可以通过web请求开始的任务。当该请求被路由到控制器,控制器将创建一个新的可运行此任务并启动线程运行任务。因此,原来的线程将返回并放入ThreadLocal中(用的OpenSessionInViewFilter)Hibernate的Session不可用任务的新线程。因此,当任务没有一些数据库的东西,我得到了臭名昭著的LazyInitializationException中。

The Problem: I have a task which can be started via a web request. When the request is routed to a controller, the controller will create a new Runnable for this task and start the thread to run the task. So the original thread will return and the Hibernate session which was put in ThreadLocal (by OpenSessionInViewFilter) is not available to the new thread for the Task. So when the task does some database stuff I get the infamous LazyInitializationException.

任何一个可以建议我可以提供给任务?

Can any one suggest the best way I can make a Hibernate session available to the Task?

感谢您的阅读。

推荐答案

请您的Runnable 一个Spring bean,并添加 @Transactional 标注了运行。您必须警告你,这种异步任务不会在同一事务作为您的网络请求运行。

Make your Runnable a Spring bean and add @Transactional annotation over run. You must be warned thou that this asynchronous task won't run in the same transaction as your web request.

和请不要启动新的线程,使用池/执行人。

And please don't start new thread, use pooling/executor.

这篇关于Hibernate会话线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆