Hibernate配置错误处理

本文探讨了Hibernate3中常见的两个错误:NoCurrentSessionContextConfigured与NoTransactionManagerLookup指定,并介绍了如何通过配置和使用不同的Session方法来解决这些问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

错误1:解决HIbernate3运行出现No CurrentSessionContext configured!错误

是由于函数getcurrentsession()造成的,可以将其改为opensession(),也可以进行一下修改:
修改配置文件:hibernate.cfg.xml,根据运行环境添加如下配置:
1)在容器中运行即在集成环境下(例如Jboss),在hibernate.cfg.xml中session-factory段加入:

<property name="current_session_context_class">jta</property>

2) 独立运行:即在不集成Hibernate的环境下(例如使用JDBC的独立应用程序),在hibernate.cfg.xml中session-factory段加入:

<property name="current_session_context_class">thread</property>

注:hibernate.cfg.xml文件中内容的编写是有顺序的:先“property”,然后是“mapping”,以上内容是“property”,应在“mapping”之上。

​错误2:hibernate3, No TransactionManagerLookup specified

Session session=sessionFactory.opensession()

而不是:Session session=sessionFactory.getCurrentSession()

openSession()与getCurrentSession()区别:

  1. getCurrentSession创建的session会和绑定到当前线程,而openSession不会。
  2. getCurrentSession创建的线程会在事务回滚或事物提交后自动关闭,而 openSession必须手动关闭。这里getCurrentSession本地事务(本地事务:jdbc)时要在配置文件里进行如下设置:

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

  3. getCurrentSession () 使用当前的session,openSession() 重新建立一个新的session
  4. 在一个应用程序中,如果DAO 层使用Spring 的hibernate 模板,通过Spring 来控制session 的生命周期,则首选getCurrentSession ()。
  5. .在 SessionFactory 启动的时候, Hibernate 会根据配置创建相应的 CurrentSessionContext ,在 getCurrentSession() 被调用的时候,实际被执行的方法是 CurrentSessionContext.currentSession() 。在 currentSession() 执行时,如果当前 Session 为空, currentSession 会调用 SessionFactory 的 openSession 。所以 getCurrentSession() 对于 Java EE 来说是更好的获取 Session 的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值