I am getting the following error message when trying to refer to the current session in an application using spring and hibernate 4:
SEVERE: Servlet.service() for servlet [spring] in context with path [/DocumentManager] threw exception [Request processing failed;
nested exception is org.hibernate.HibernateException:
No Session found for current thread] with root cause org.hibernate.HibernateException:
No Session found for current thread
The error message is triggered by sessionFactory.getCurrentSession() in the following line of code in a controller class:
Blob blob = Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(file.getInputStream(), file.getSize());
Here is the block of code in which it resides:
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("document") Document document, @RequestParam("file") MultipartFile file) {
try {
Blob blob = Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(file.getInputStream(), file.getSize());
document.setFileName(file.getOriginalFilename());
document.setContent(blob);
document.setContentType(file.getContentType());
} catch (IOException e) {e.printStackTrace();}
try {documentDao.save(document);}
catch(Exception e) {e.printStackTrace();}
return "redirect:/index.html";
}
I tried axtavt's answer in this posting, but eclipse started forcing a lot of changes that would propagate to other parts of the application, such as making doInTransactionWithoutResult() protected and thus forcing my document variable to become final in scope.
My application does have a transactionManager bean as follows:
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
But how do I modify the code (above) inside my controller class so that it can getCurrentSession() without throwing the error?