Dilan
Dilan

Reputation: 1449

Retrieving sessions using getCurrentSession() and openSession() in Hibernate

I am new to hibernate and I have a little confusion in retrieving sessions using getCurrentSession() and openSession(), many articles mentioned that getCurrentSession creates a brand new session if one is not already existing and does not create a new session if a session is already available, and on the other hand openSession creates a brand new session.

  1. Here I have a confusion does openSession() always creates a brand new session?
  2. Does hibernate pools sessions to uses the same session in the getCurrentSession()?

Can you please help me to clarify this and apologies for any mistake I made

thanks a lot

Upvotes: 0

Views: 518

Answers (1)

Yogesh
Yogesh

Reputation: 4784

  1. Yes. openSession() binds the session to the current context. Default context is Thread, it can also be bound on HttpRequest level using custom filter or OpenSessionInViewFilter
  2. No. Hibernate does not have actual connection pool out the box. Have a look at this question. A session is opened whenever getCurrentSession() is called for the first time in that particular context. after that to find already existing session Hibernate uses CurrentSessionContext to determine current context and will return session bound to that particular context. Majority of Application Servers associates a session with a Thread which is created using the underlying ThreadLocal object.

Upvotes: 1

Related Questions