关于在Spring中Hibernate的No Session found for current thread问题
2014-07-17 13:12
746 查看
在我们的项目框架中,Hibernate配置Session方式有两种
一种是aop方式,如下图
一种是注解的方式,如下图
这两种方式的使用方式是有区别的,区别在于写Service实现类(即XxxServiceImpl)时,aop方式不需要任何的操作,只需要写上@Service注解即可,如下图:
而注解方式则需要在你所实现的方法上加上注解@Transactional即可,如下图:
在XxxServiceImpl使用注解的方式固然可行,但写程序时要注意效率,不可能在每个XxxServiceImpl下的每个方法写上@Transactional,因此,下面这种方法是优化的方法,即在XxxDaoImpl下写上@Transactional,如下图
注意这之间两图的差异:
图一
图二
在配置spring时,为什么要用这两种方式呢?主要是在Dao设计时,我们采用的是Hibernate的SessionFactory.getCurrentSession()方法。如下图:
如果不想在spring中配置,那么在Dao中的方法我们也将改,将采用Hibernate的SessionFactory.openSession()方法。如下图
采用openSession()后必须记住要手动关闭,而getCurrentSession()则是自动关闭的。
如果不采用以上几种方法,那么将会报异常“HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread”。
一种是aop方式,如下图
一种是注解的方式,如下图
这两种方式的使用方式是有区别的,区别在于写Service实现类(即XxxServiceImpl)时,aop方式不需要任何的操作,只需要写上@Service注解即可,如下图:
而注解方式则需要在你所实现的方法上加上注解@Transactional即可,如下图:
在XxxServiceImpl使用注解的方式固然可行,但写程序时要注意效率,不可能在每个XxxServiceImpl下的每个方法写上@Transactional,因此,下面这种方法是优化的方法,即在XxxDaoImpl下写上@Transactional,如下图
注意这之间两图的差异:
图一
图二
在配置spring时,为什么要用这两种方式呢?主要是在Dao设计时,我们采用的是Hibernate的SessionFactory.getCurrentSession()方法。如下图:
如果不想在spring中配置,那么在Dao中的方法我们也将改,将采用Hibernate的SessionFactory.openSession()方法。如下图
采用openSession()后必须记住要手动关闭,而getCurrentSession()则是自动关闭的。
如果不采用以上几种方法,那么将会报异常“HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread”。
相关文章推荐
- 关于Spring3.2+Hibernate4.1整合问题:No Session found for current thread
- Hibernate4 与 spring3 集成之后 “No Session found for current thread”
- Spring 3 和 Hibernate4 整合时遇到的 No Session found for current thread !
- SpringMVC3+Hibernate4问题:org.hibernate.HibernateException: No Session found for current thread
- spring3 与 Hibernate4集成报错 No Session found for current thread
- Spring-Hibernate - No Session found for current thread
- No Sessionfound for current thread问题:hibernate.current_session_context_class
- Spring3 + Hibernate4 配置 No Session found for current thread问题的解决
- 关于异常: org.hibernate.HibernateException: No Session found for current thread
- Hibernate4 与 spring3 集成Hibernate4 No Session found for current thread
- Spring整合hibernate No Session found for current thread
- org.hibernate.HibernateException: No Session found for current thread
- Spring framework3.2整合hibernate4.1报错:No Session found for current thread
- Hibernate4 No Session found for current thread原因
- org.hibernate.HibernateException: No Session found for current thread
- SpringMVC 整合 hibernate 报错:No Session found for current thread
- org.hibernate.HibernateException: No Session found for current thread
- Spring framework3.2整合hibernate4.1报错:No Session found for current thread
- Hibernate4 No Session found for current thread原因
- org.hibernate.HibernateException: No Session found for current thread