spring hibernate Async task issue No Session found for current thread

烈酒焚心 提交于 2019-12-10 21:03:56

问题


This is my method to save data . It is working fine

    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);
    }

But if I put @Async annotion on method I've got the following exception.

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)

If anyone have knowledge about this exception, I appreciate. thanks


回答1:


From here

It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from a SessionFactory.

According to documentation threads should have their own sessions. If you get session by sessionFactory.getCurrentSession(); you'll get null because its' access protected by ThreadLocals.

You can create new session for per thread by this code.

@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);
    }


来源:https://stackoverflow.com/questions/41297127/spring-hibernate-async-task-issue-no-session-found-for-current-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!