当我尝试使用 spring 和 hibernate 4 引用应用程序中的当前 session 时,收到以下错误消息:
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
错误消息由 Controller 类中以下代码行中的 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() protected ,从而强制我的文档变量在范围内成为最终变量。
我的应用程序确实有一个 transactionManager bean,如下所示:
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
但是我如何修改 Controller 类中的代码(上面),以便它可以 getCurrentSession() 而不抛出错误?
最佳答案
添加此<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
class DocumentDaoImpl
{
public void save(document){
}
public void someMethod(){
}
}
注意:
将这些类型的 hibernate 相关代码移至 DocumentDaoImpl
Blob blob = Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(file.getInputStream(), file.getSize());
关于java - 如何在 hibernate 4 中定义获取 session 的事务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20134772/