The server uses HibernateSession to prevent No session.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.