spring 休眠异步任务问题没有找到当前线程的会话

spring hibernate Async task issue No Session found for current thread

这是我保存数据的方法。工作正常

    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(); 获得会话,您将得到空值,因为它的访问受 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);
    }