A new thread needs to bind a Hibernate session to use functions such as transactions and delayed loading in the new thread. Otherwise, no session exception occurs;
Solution:
New Runnable () {@ Override public void run () {// ---------- bind session to the current thread ---------- SessionFactory sessionFactory = (SessionFactory) applicationContext. getBean ("sessionFactory"); boolean maid = ConcurrentUtil. bindHibernateSessionToThread (sessionFactory); // --------- your business ---------------// ---------- Close session ------------ ConcurrentUtil. closeHibernateSessionFromThread (participant, sessionFactory );}}
BindHibernateSessionToThread method: 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; }
CloseHibernateSessionFromThread Method public static void closeHibernateSessionFromThread(boolean participate, Object sessionFactory) { if (!participate) { SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.unbindResource(sessionFactory); SessionFactoryUtils.closeSession(sessionHolder.getSession()); } }
The transaction boundary is controlled by the aop or Transactional mark. The sample code only ensures that the transaction method can obtain the session object from the current thread as needed.
Most of the above Code is intercepted from Spring's OpenSessionInViewFilter.