File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes Importance of ThreadLocal in hibernate Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Importance of ThreadLocal in hibernate" Watch "Importance of ThreadLocal in hibernate" New topic

Importance of ThreadLocal in hibernate

liliane fahmy

Joined: Aug 24, 2012
Posts: 22
Please I want to know the importance of ThreadLocal in generaly and also in this following code ,
what 's the purpose of getting session by get() of ThreadLocal ?

public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();

Please reply me
Thanks you
jatan bhavsar
Ranch Hand

Joined: Jul 23, 2008
Posts: 297

Hi Liliane,

Threadlocal is used to create session for everythread.It will make sure that everyuser accessing web page will get its own session. So here threadlocal is used basically to provide different session to different thread.

Bill Gorder

Joined: Mar 07, 2010
Posts: 1682

Just a note you should most likely not be writing code like that in your application anyway. Hibernate comes with a ThreadLocalSessionContext where sessions are tracked by thread of execution. This should be used for that use case rather than attempting to roll your own. This can be used by simply setting a hibernate property. Please see the reference documentation for more details.

[How To Ask Questions][Read before you PM me]
I agree. Here's the link:
subject: Importance of ThreadLocal in hibernate
It's not a secret anymore!