当尝试使用spring和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
错误消息由控制器类中以下代码行中的sessionFactory.getCurrentSession()触发:
Blob blob = Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(file.getInputStream(), file.getSize());
以下是它所在的代码块:
@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";
}
我尝试了axtavt's answer in this posting,但是eclipse开始强制进行大量的更改,这些更改会传播到应用程序的其他部分,例如使doInTransactionWithoutResult()受到保护,从而迫使我的文档变量成为范围的最终变量。
我的应用程序确实有一个transactionManager bean,如下所示:
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
但是如何修改我的控制器类中的代码(上面)以便它可以getCurrentSession()而不会抛出错误?
答案 0 :(得分:1)
添加此<tx:annotation-driven transaction-manager="transactionManager" />
在你的背景下。
请参阅此链接,它可能会对您有所帮助。
Spring Hibernate transaction management
How to integrate spring with hibernate session and transaction management?
Automatic Hibernate Transaction Management with Spring?
修改
这里的DocumentDaoImpl中的save方法只是Transactional。
class DocumentDaoImpl
{
@Transactional
public void save(document){
}
public void someMethod(){
}
}
或
这里DocumentDaoImpl中的所有方法都是Transactional。
@Transactional
class DocumentDaoImpl
{
public void save(document){
}
public void someMethod(){
}
}
注意:
将这些类型的与休眠相关的代码移动到DocumentDaoImpl
Blob blob = Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(file.getInputStream(), file.getSize());