I was googling a bit on "No Hibernate Session bound to thread". Emphatically, I ended up with innumerous answers in several sites on the Internet. Springsource forum is not exception to this! Abundant conversations have been happening on this topic all around!!!
But there were a few best practices that I was able to compile from the chit-chats happening across the Internet. I thought of sharing the same here so that it would help some one some day in the near future!
- First and foremost, configure the transaction manager properly : Use @Transaction annotation near your code and have a transactionManager bean in your spring config file.
- when integration a transaction manager, do not use hibernate.current_session_context_class and hibernate.transaction_factory_class in the hibernate properties unless you have proper reasons to
- Never call sessionFactory.openSession()
- Use ApplicationContext rather than using BeanFactory
- Have single dao instances running across the Application
- Above all, most importantly, ensure that the current application context has the component scan for the beans where you have added the @transactional annotations. as per spring documentation's @ Trasactional usage guidelines,
Point # 6 was the culprit in our case and that was then resolved! So the lessson was You are likely to get "No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here" if you do not adhere to any of the above pointers.
<tx:annotation-driven/>only looks for
@Transactionalon beans in the same application context it is defined in. This means that, if you put
DispatcherServlet, it only checks for
@Transactionalbeans in your controllers, and not your services. See Section 15.2, “The DispatcherServlet” for more information.
PArticularly, if you are going to have the applicationContext.xml with the TxManager and the servletname-servlet.xml with the component scan annotations, then you are more likely to get this "No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here" exception since the TxManager's transaction holds good for the current application context only (which in this case does not have the bean definitions for the service or the daos where you have the @ Trasactional annotations)
If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!