开发者

When to open/close a hibernate session in a Java EE enviroment

开发者 https://www.devze.com 2023-04-06 10:31 出处:网络
Open at the begin of the http request and close at the end and each http request is treated in a separated thread?

Open at the begin of the http request and close at the end and each http request is treated in a separated thread?

Maybe saving all session in a HashMap and access it statically?

Any in开发者_JAVA技巧formation which explains how hibernate sessions work (or what they really are) are helpful.


If at the beginning of request/end of request means the http Request, then this is usually done by a servlet filter which opens/closes session for you. This design pattern is called OpenSessionInView (Filter). You can get details here.

This pattern is useful only if you application is rendered in same JVM where Hibernate Session exists. If Your data access tier resides on different JVM than your view rendering tier, you will have to (eagerly) fetch all the required model beans before dispatching the request for rendering of the view .

If you are using spring (or EJB3), you can get the Session (EntityManager) injected in your Data Access classes so you wont need to manually work on Opening and closing the session.

Ideally, you should not need to manually open/close session/transaction (because it leaves chances of missing out a session.close() or tx.commit() and the likes). Instead use the container provided JPA entitymanager or use spring to manage it for you.


There are multiple patterns of using the session, but the most common and usually the proper one is to open and close it on each request (=thread=unit of work)

In a JavaEE environment you would normally make use of JPA. So use hibernate through the EntityManager, which can be injected in components (like EJBs or cdi managed beans) with @PersistenceContext


usually a session is open when accessing data store is needed (e.g. transaction begins). When to close it has different patterns and approaches. you could keep the session open in views (jsps). but you don't have to do that.

e.g. one of our project doesn't allow to use opensessionInView filter. So the session was closed after transaction ended. All data (Value objects basically) need to send to view were loaded before dispatching.

0

精彩评论

暂无评论...
验证码 换一张
取 消