【JAVA】No Session found for current thread

o如果你的项目用spring3+hibernate4+struts2构建的web项目,或许你也碰到了在执行数据库操作时出现:

org.hibernate.HibernateException: No Session found for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)

这样的错误,或者saveOrUpdate明明执行了却没有更新修改!!!你以为是没有配置current_session_context.class为thread?也不是!

作为java web的菜鸟,虽然写了一年的代码了,但是这个问题,让我郁闷许久,以前碰到了,都让我忽略了,这次做的一个项目,竟然还碰到了,让我难以容忍,在各种百度搜索之后,终于,让真相浮出水面。

最终解决办法在web.xml配置openSessionInViewFilter这个过滤器就可以了,web.xml增加如下:

 <!-- openSessionInViewFilter -->
   <filter>
         <filter-name>openSessionInViewFilter</filter-name> 
         <filter-class> 
         org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
         </filter-class> 
         <!-- 指定在spring配置的sessionFactory(默认名为sessionfactory)-->
        <init-param> 
            <param-name>sessionFactoryBeanName</param-name> 
            <param-value>sessionFactory</param-value> 
        </init-param> 
             <!-- singleSession默认为true,若设为false则等于没用OpenSessionInView -->   
        <init-param> 
         <param-name>singleSession</param-name> 
        <param-value>true</param-value> 
        </init-param> 
    </filter>
    ········
    <filter-mapping>
       <filter-name>openSessionInViewFilter</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>

为什么这样就可以解决问题了呢?请查看spring3文档:http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/orm/hibernate4/support/OpenSessionInViewFilter.html
其中写到:
This filter makes Hibernate Sessions available via the current thread, which will be autodetected by transaction managers. It is suitable for service layer transactions via HibernateTransactionManager as well as for non-transactional execution (if configured appropriately).
这个过滤器就是自动检测事务管理的当前线程使得hibernate session可用,而且可以运用到配置了事务和没有事务层的service层。所以,如果没有配置这个过滤器,自然你用getcurrentSession是找不到的session的。

注意 :使用 hibernate4,在不使用OpenSessionInView模式时,在使用getCurrentSession()时会有如下问题:

当有一个方法list 传播行为为Supports,当在另一个方法getPage()(无事务)调用list方法时会抛出org.hibernate.HibernateException: No Session found for current thread 异常。
这是因为getCurrentSession()在没有session的情况下不会自动创建一个,不知道这是不是Spring3.1实现的bug,欢迎大家讨论下。

因此最好的解决方案是使用REQUIRED的传播行为。

参考博客:
http://www.oschina.net/question/659963_87447?fromerr=Uacffrx8
http://stackoverflow.com/questions/15939932/hibernateexception-no-session-found-for-current-thread-when-calling-service-from

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值