spring hibernate Async task issue No Session found for current thread

1.5k views Asked by At

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

There are 1 answers

0
Ömer Erden On BEST ANSWER

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