Spring + Hibernate会话生命周期 [英] Spring + Hibernate session lifecycle

查看:111
本文介绍了Spring + Hibernate会话生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



创建 SessionFactory

创建一个Hibernate会话的生命周期应该如何正确完成? Spring会自动进行连接,并从Glassfish连接池中获取数据库连接。目前,我通过 SessionFactory.getCurrentSession()获取Hibernate会话。然后我开始交易,完成工作,然后结束 commit()或 rollback()。是否需要执行其他任何操作,如 disconnect() close() flush ()或其他任何时候,所以连接将被正确地返回到池中,或者Spring已经自动完成了所有的事情?

有了这些方法,我现在有点困惑,理解什么时候应该做什么,也许有人可以指向正确的方向?

解决方案

由于SessionFactory是Spring自动创建的,Spring框架将负责关闭连接。
查看 Spring资源管理



如果你想检查。如果您正在为应用程序使用日志记录,则可以检查日志。它将如下所示:
$ b


(main)INFO [AnnotationSessionFactoryBean]关闭Hibernate SessionFactory


我从此链接


这里的主要契约是创建Session实例。通常
应用程序具有一个SessionFactory实例,并且线程
服务于客户端请求,从该工厂获取Session实例。
SessionFactory的内部状态是不可变的。一旦它创建了
,就设置了这个内部状态。这个内部状态包括关于对象/关系映射的元数据的所有

实现者必须是线程安全的。



How properly "lifecycle" of a Hibernate session under Spring should be done?

The SessionFactory is created automatically by Spring and is taking its DB connections from Glassfish connection pool. At the moment I am getting a Hibernate session via SessionFactory.getCurrentSession(). Then I start transaction, do the work and then commit() or rollback() at the end. Do I need to do any other actions like disconnect(), close(), flush() or any others at any time so connections would be properly returned back to the pool or is everything already automatically done by Spring?

With plenty of these methods it is a little confusing for me at the moment to understand when what should be done, maybe someone can point to right direction?

解决方案

As SessionFactory is created automatically by Spring, Spring framework will take care of closing the connection. Check out Spring Resource Management

If you want to check. You can check the log, if you are using logging for your app. It'll be like :

(main) INFO [AnnotationSessionFactoryBean] Closing Hibernate SessionFactory

I get following lines from this link

The main contract here is the creation of Session instances. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory. The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping. Implementors must be threadsafe.

这篇关于Spring + Hibernate会话生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆