分享

Hibernate openSession 和 getCurrentSession区别

 hh3755 2012-03-14

Hibernate openSession 和 getCurrent

发布日期:11-10-24 05:09    文章来源:互联网

1.采用getCurrentSession()创建的Session会绑定到当前的线程中去;

而采用OpenSession()则不会。

2.采用getCurrentSession()创建的Session在commit或rollback后会自动关闭;

采用OpenSession()必须手动session.close()关闭。

3.采用getCurrentSession()需要在Hibernate.cfg.xml配置文件中加入如下配置:

未绑定当前线程会出现异常:

org.hibernate.HibernateException:No Hibernate Session bound to thread

*如果使用的是本地事务(jdbc事务)<propertyname="hibernate.current_session_context_class">thread</property>* 如果使用的是全局事务(jta事务)

<propertyname="hibernate.current_session_context_class">jta</property>

另外,但是在使用getCurrentSession(),必须在事务中运行,要不出

org.hibernate.HibernateException:?createQueryis not valid without active transaction

但是,配上事务后只有将

<propertyname="hibernate.current_session_context_class">thread</property>去掉,程序才能运行这不是前后矛盾么!???难道spring在通过sessionFactory获取session时,没有调用getCurrentSession()方法。通过加入事务,提交,所以不需要配置getCurrentSession?

在Hibernate3.2中使用getCurrentSession,只需将其放入一个事务中即可!


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多