简体   繁体   English

打开休眠会话而不关闭它的影响

[英]Impact of opening a hibernate session and not closing it

I lately observed a problem in my code, I opened a hibernate session but forgot to close it. 我最近在代码中发现一个问题,我打开了一个休眠会话,但忘记关闭它了。 Although I fixed it but I can't seem to understand the impact of this mistake I did. 尽管我已解决问题,但似乎无法理解我所做的此错误的影响。

This code was in HTTP service, I need answers for two cases: 这段代码在HTTP服务中,我需要两种情况的答案:

  1. The container spawns a new thread when a request comes 当请求到来时,容器会产生一个新线程
  2. It fetches from thread pool 它从线程池中获取

I have read in other posts that session is bound to thread, so what I have inferred from that is if a new thread is spawned in each request and I have left a session open in one of them. 我在其他帖子中已经读到会话绑定到线程,因此我可以推断出,如果在每个请求中都产生了一个新线程,而我却在其中一个会话中打开了会话。 It will be then destroyed when request gets completed. 请求完成后将销毁它。 I dont know I am right or not. 我不知道我是对还是错。

It depends of what you use to control a session life cycle. 这取决于您用来控制会话生命周期的内容。 If you use a "session per request pattern" with, for an example, OpenSessionInViewFilter , a session will be closed by a filter. 例如,如果将“每个请求的会话模式”与OpenSessionInViewFilter一起使用 ,则会话将被过滤器关闭。 You can use your own filter to control a session as well. 您也可以使用自己的过滤器来控制会话。

If you don't use filters or similar stuff you should always close a session. 如果您不使用过滤器或类似内容,则应始终关闭会话。 Threads that process requests know nothing about Hibernate session. 处理请求的线程对Hibernate会话一无所知。

SessionFactory.openSession() always open a new session. SessionFactory.openSession()始终打开一个新会话。

SessionFactory.getCurrentSession() do a check, if the current session exists — return it, if the current session doesn't exist — create a new one. SessionFactory.getCurrentSession()会检查当前会话是否存在,如果当前会话不存在,则将其返回-创建一个新会话。 A meaning of "current session" depends of a session factory parameters. “当前会话”的含义取决于会话工厂参数。 In the classical case, a session is bounded to the thread (as you describe), but it can be bounded to the transaction, for an example. 在经典情况下,会话绑定到线程(如您所描述的),但是例如,它可以绑定到事务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM