zoukankan      html  css  js  c++  java
  • 关于Hibernate Could not obtain transaction-synchronized Session for current thread

    转载自 http://blog.csdn.net/flyjiangs/article/details/51537381

    最近几年一直再搞android,最近闲下来了,顺便玩一下web。

    整了个最新版本的SSH(hibernate5.1.0+spring4.2.6+struts-2.5)

    在写dao实现类的时候碰到一个问题,

    @Repository  
    public class UserDaoImpl implements IUserDao {  
      
        @Autowired  
        private SessionFactory sessionFactory;  
      
        private Session getSession(){  
            return sessionFactory.getCurrentSession();  
              
        }  
        ...   
    }

    用了sessionFactory.getCurrentSession()这个之后,会提示

    org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread 这个异常。(据说hibernate 4以上的版本才会有)

    这里可以用Session session = sessionFactory.openSession(),然后代码中去关闭 session.close.当然为了偷懒的原则

    必须不自己去管理session。让Spring容器自己去处理。

    研究了一下。发现 只要在

    applicationContext.xml 中追加

    <!-- 配置事务管理器 -->   
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">   
        <property name="sessionFactory" ref="sessionFactory"></property>   
    </bean>  
           
    <tx:annotation-driven transaction-manager="transactionManager"/>

    然后再在实现类加上@Transactional

    @Repository  
    @Transactional  
    public class UserDaoImpl implements IUserDao {  
      
        @Autowired  
        private SessionFactory sessionFactory;  
      
        private Session getSession(){  
            return sessionFactory.getCurrentSession();  
              
        }  
        ...   
    }

    这样问题就完美解决了。

  • 相关阅读:
    c# 集合运算
    Nuxt
    引入js,不共享变量
    sourcetree将存在的本地项目提交到远程仓库
    c#DateTime与unix时间戳互相转换
    IfcBoundingBox
    IfcBooleanResult
    IfcAnnotationFillArea
    IfcGeometricRepresentationItem
    IfcRepresentationItem
  • 原文地址:https://www.cnblogs.com/wpcnblog/p/8548398.html
Copyright © 2011-2022 走看看