这是我保存数据的方法。工作正常
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.
根据文档,线程应该有自己的 session 。如果您通过 sessionFactory.getCurrentSession();
获取 session ,您将得到 null,因为它的访问受 ThreadLocals 保护。
您可以通过此代码为每个线程创建新 session 。
@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);
}
关于java - spring hibernate 异步任务问题 No Session found for current thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41297127/