【发布时间】:2015-10-05 00:56:32
【问题描述】:
我有一个基于 Spring 4.0 和 Hibernate 4 的项目,特别是 Spring MVC。
Hibernate 的会话由OpenSessionInViewFilter 为控制器中的每个请求创建。
现在,我正在尝试在控制器的方法中启动一个新线程(执行一个漫长的过程)。显然,OpenSessionInViewFilter 正在请求完成后关闭会话。然后,当我的线程启动时,不再有会话,我收到此错误:
org.hibernate.HibernateException: No Session found for current thread
这是类的基本结构,从 Controller 到我的 Callable 组件。 IReportService 扩展了 Callable。
OBS:我曾尝试使用 spring 的 @Async 注释,但它仍然无法正常工作。我将 REQUIRES_NEW 放在 Service 上试图获取新事务,但它甚至更改为 NESTED 都失败了。
@Controller
@RequestMapping(value = "/action/report")
@Transactional(propagation = Propagation.REQUIRED)
public class ReportController {
@Autowired
private IReportService service;
private final Map<Long, Future> tasks = new HashMap();
@RequestMapping(value = "/build")
public String build(@RequestParam Long id) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<StatusProcesso> future = executor.submit(service);
tasks.put(id, future);
return "wait-view";
}
@RequestMapping(value = "/check", method = RequestMethod.GET)
public @ResponseBody Map<String, Object> check(@RequestParam Long id) {
String status = null;
try {
Future foo = this.processos.get(id);
status = foo.isDone() ? "complete" : "building";
} catch (Exception e) {
status = "failed";
}
return new ResponseBuilder()
.add("status", status)
.toSuccessResponse();
}
// Another operations...
}
@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class ReportService implements IReportService {
@Autowired
private IReportDAO dao;
@Override
public Status call() {
Status status = new Status();
// do long operation and use DAO...
return status;
}
}
【问题讨论】:
标签: java multithreading spring hibernate spring-mvc