![](/img/trans.png)
[英]How do I “obtain transaction-synchronized Session for current thread” in a Micronaut / Kotest / Hibernate test
[英]how do i define transaction for getting session in hibernate 4?
當嘗試使用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的答案 ,但是eclipse開始強制進行許多更改,這些更改會傳播到應用程序的其他部分,例如使doInTransactionWithoutResult()受保護,從而迫使我的文檔變量在作用域中成為最終狀態。
我的應用程序確實有一個transactionManager bean,如下所示:
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
但是,如何修改控制器類中的代碼(上面),使其可以在不拋出錯誤的情況下進行getCurrentSession()?
將此<tx:annotation-driven transaction-manager="transactionManager" />
到您的上下文中。
看到此鏈接可能會對您有所幫助。
編輯
這里的save方法僅在DocumentDaoImpl中為Transactional。
class DocumentDaoImpl
{
@Transactional
public void save(document){
}
public void someMethod(){
}
}
要么
這里DocumentDaoImpl中的所有方法都是事務性的。
@Transactional
class DocumentDaoImpl
{
public void save(document){
}
public void someMethod(){
}
}
注意:
將這些與休眠相關的代碼類型移動到DocumentDaoImpl
Blob blob = Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(file.getInputStream(), file.getSize());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.