春季休眠异步任务问题未找到当前线程的会话
作者:互联网
这是我保存数据的方法.一切正常
public Future<SocialLogin> loginUserSocial(Social model) {
Session session = this.sessionFactory.getCurrentSession();
session.save(model);
SocialLogin dto = new SocialLogin();
dto.setUser_id(model.getUser_id());
return new AsyncResult<SocialLogin>(dto);
}
但是如果我将@Async注释放在方法上
我有以下例外.
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.util.concurrent.ExecutionException: org.hibernate.HibernateException: No Session found for current thread
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
如果有人知道此例外,我将不胜感激.
谢谢
解决方法:
从here
It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from a SessionFactory.
根据文档,线程应具有自己的会话.如果您通过sessionFactory.getCurrentSession()获得会话;您将获得null,因为它的访问受ThreadLocals保护.
您可以通过此代码为每个线程创建新会话.
@Async
public Future<SocialLogin> loginUserSocial(Social model) {
Session session = this.sessionFactory.openSession();
session.save(model);
SocialLogin dto = new SocialLogin();
dto.setUser_id(model.getUser_id());
return new AsyncResult<SocialLogin>(dto);
}
标签:completable-future,multithreading,hibernate,spring,java 来源: https://codeday.me/bug/20191111/2023275.html