(transfer) the server opens a new Multithread to use HibernateSession to prevent No session

Keywords: Session Hibernate Spring

Original link of blogger: https://blog.csdn.net/zhengwei223/article/details/30506455

The new thread needs to bind the Hibernate session to use the functions of transaction and delay loading in the new thread, otherwise no session exception will be exposed;

terms of settlement:

//Business method
new Runnable() {  
    @Override  
    public void run() {  
        //----------Bind session to current thread------------  
        SessionFactory sessionFactory = (SessionFactory)applicationContext.getBean("sessionFactory");  
        boolean participate = ConcurrentUtil.bindHibernateSessionToThread(sessionFactory);  
        //---------Your business---------------  
        //TODO hello.
        // ----------Close session------------                     
        ConcurrentUtil.closeHibernateSessionFromThread(participate, sessionFactory);  
    }        
} 

//Tool method: bindhibernatesessionthread
public static boolean bindHibernateSessionToThread(SessionFactory sessionFactory) {  
    if (TransactionSynchronizationManager.hasResource(sessionFactory)) {  
        // Do not modify the Session: just set the participate flag.  
        return true;  
    } else {  
        Session session = sessionFactory.openSession();  
        session.setFlushMode(FlushMode.MANUAL);  
        SessionHolder sessionHolder = new SessionHolder(session);  
        TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);  
    }  
    return false;  
}  
//Tool method: closeHibernateSessionFromThread
public static void closeHibernateSessionFromThread(boolean participate, Object sessionFactory) {  

    if (!participate) {  
        SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.unbindResource(sessionFactory);  
        SessionFactoryUtils.closeSession(sessionHolder.getSession());  
    }  
}  

Transaction boundaries are controlled by aop or Transactional tags,
The sample code only guarantees that the transactional method can obtain the session object from the current thread when necessary.
Most of the above code is intercepted from Spring's opensessioninview filter.

PS: reproduced from https://blog.csdn.net/zhengwei223/article/details/30506455

Posted by mourisj on Fri, 03 Apr 2020 10:28:25 -0700