Reputation: 9191
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?
Upvotes: 1
Views: 886
Reputation: 26094
add this <tx:annotation-driven transaction-manager="transactionManager" />
to your context.
see this links it might help you.
Spring Hibernate transaction management
How to integrate spring with hibernate session and transaction management?
Automatic Hibernate Transaction Management with Spring?
edit
here the save method in DocumentDaoImpl only Transactional.
class DocumentDaoImpl
{
@Transactional
public void save(document){
}
public void someMethod(){
}
}
or
here all the methods in DocumentDaoImpl are Transactional.
@Transactional
class DocumentDaoImpl
{
public void save(document){
}
public void someMethod(){
}
}
Note:
Move these type of hibernate related code to DocumentDaoImpl
Blob blob = Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(file.getInputStream(), file.getSize());
Upvotes: 1