Managing Transactions with Hibernate - Hibernate in the Real World: Implementing a Utility class for Hibernate
(Page 3 of 4 )
Until now I've been creating the configuration, building the session and retrieving the transaction object whenever a requirement arose. Though in the last part the CRUD related functionality was shifted to a separate class, the steps needed to initialize the Hibernate framework were not modularized or made generic so that they could be reused. That is what I am going to do in this section. But before going ahead with the utility class, one more concept has to be introduced: Thread Local Variables.
These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or transaction ID). In short, threads would have their own copy of the thread local variables. While its true that there would be only one ThreadLocal variable, that variable would hold multiple instances of the desired object. In our case that would be the session object.
Now that I've given you an overview of the concept of a Thread Local Variable, let's get started with the implementation details of the Hibernate utility class. For the sake of convention it has been name HibernateUtility.
First comes the package name and imports:
package com.someorg.persist;
import org.hibernate.*;
import org.hibernate.cfg.*;
Next come the class
public class HibernateUtility {
:
:
}
Since the class is following the factory pattern, all the methods would be static and there would be no constructor as such. Here I would like to point out that there can be varied implementation of a pattern. There is no hard and fast implementation of any pattern. Also the initializations are done in a static block:
public class HibernateUtility {
public static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from
hibernate.cfg.xml
sessionFactory = new
Configuration().configure
().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it
might be swallowed
System.err.println("Initial SessionFactory
creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
:
:
}
Then comes the thread local variable:
public class HibernateUtility {
public static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new
Configuration().configure
().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be
swallowed
System.err.println("Initial SessionFactory creation
failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session = new
ThreadLocal();
:
:
}
Now come the methods that provide session management.
public class HibernateUtility {
public static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new
Configuration().configure
().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be
swallowed
System.err.println("Initial SessionFactory creation
failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws
HibernateException {
Session s = (Session) session.get();
// Open a new Session, if this thread has none
yet
if (s == null) {
s = sessionFactory.openSession();
// Store it in the ThreadLocal variable
session.set(s);
}
return s;
}
public static void closeSession() throws
HibernateException {
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
:
:
}
Each new session object is set as the Thread Local Variable. Whenever the session has to be closed, the appropriate session object is retrieved from the thread and it is closed.
Next: Implementing a Utility class for Hibernate continued >>
More Java Articles
More By A.P.Rajshekhar