Hibernate 会话的 Spring 配置

发布于 2024-09-29 21:09:04 字数 1037 浏览 0 评论 0原文

你好 我试图通过Spring的注入来获取hibernate的Session。

这是我的 spring 上下文 xml:

  <!-- hibernate's session factory -->
  <bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="configLocation">
      <value>classpath:./hibernate.cfg.xml</value>
    </property>
  </bean>

  <!-- the transaction manager -->
  <bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
  </bean>

这是代码:

private static ApplicationContext ctx;

    if (ctx == null) {
        ctx = new ClassPathXmlApplicationContext("springContext.xml");
    }
    LocalSessionFactoryBean sf = ctx.getBean(LocalSessionFactoryBean.class);
    session = sf.getObject().getCurrentSession();

但是我获得的会话为空。

通过 sf.getObject().getCurrentSession() 获取 Session 是否正确?

谢谢 :)

Hi
I'm trying to obtain hibernate's Session through Spring's injection.

Here's my spring context xml:

  <!-- hibernate's session factory -->
  <bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="configLocation">
      <value>classpath:./hibernate.cfg.xml</value>
    </property>
  </bean>

  <!-- the transaction manager -->
  <bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
  </bean>

Here's the code:

private static ApplicationContext ctx;

    if (ctx == null) {
        ctx = new ClassPathXmlApplicationContext("springContext.xml");
    }
    LocalSessionFactoryBean sf = ctx.getBean(LocalSessionFactoryBean.class);
    session = sf.getObject().getCurrentSession();

However the session I obtain is null.

Is it correct to get Session through sf.getObject().getCurrentSession() ?

Thanks :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷爱 2024-10-06 21:09:13

我认为您不应该这样访问会话。使用 HibernateTemplate 或在您的 bean 中注入 SessionFactory 并对其调用 getCurrentSession() 。否则你的交易管理将无法得到正确处理

I don't think you should access the session like that. Either use HibernateTemplate or inject SessionFactory in your beans and call getCurrentSession() on it. Otherwise your transaction management won't be handled properly

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文