I am new in hibernate,after read the hibernate api and tutorial,it seems that the session should closed when not used.
Like this:
Session sess=getSe
We can make use of ThreadLocal.
public class MyUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
private static final ThreadLocal threadLocal;
static {
try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
threadLocal = new ThreadLocal();
} catch(Throwable t){
t.printStackTrace();
throw new ExceptionInInitializerError(t);
}
}
public static Session getSession() {
Session session = threadLocal.get();
if(session == null){
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public static void closeSession() {
Session session = threadLocal.get();
if(session != null){
session.close();
threadLocal.set(null);
}
}
public static void closeSessionFactory() {
sessionFactory.close();
StandardServiceRegistryBuilder.destroy(serviceRegistry);
}
}
Here, the SessionFactory is initialized only once using the static block. Hence, whenever the main class makes a call to getSession(), the presence of Session object is first checked in the threadLocal object.
Therefore, this program provides thread-safety.
After each operation, closeSession() will close the session and set the threadLocal object to null.
Finally call the closeSessionFactory().