Hibernate is an Object Relation mapping framework for Java language. It has more benefits over JDBC. Since I am using it since 2010, I have found that one of the biggest benefits of Hibernate is that code written using Hibernate is almost database independent and can be a key feature if one wants to shift the code base from one database to another.
Using Hibernate, one has to be careful with the following two
Using Hibernate, one has to be careful with the following two
a) A singleton SessionFactory instance should be maintained throughout the application (if using a single database)
It can be easily done using either a static code block OR implementing the Singleton pattern.b) Single Session instance should be maintained per Thread
This is a tricky part but luckily we have the ThreadLocal to our rescue. This class provides thread-local variables. Below is the code to maintain a single Session instance per Thread
private static final ThreadLocal<Session> session = new ThreadLocal<Session>();
public static Session getCurrentSession() {
Session s = (Session) session.get();
// Open a new Session, if this Thread has none yet
if ( (s==null) || (!s.isOpen()) ) {
s = sessionFactory.openSession();
session.set(s);
}
return s;
}
Please leave your comments below if this post helped you.
Comments
Post a Comment