I am using Hibernate 4.3. I am trying to get the SessionFactory
object from a HibernateUtil
class. I am trying to get only one SessionFactory
object for entire application, i.e. Singleton object for application.
Below is my current code, I want to make it Singleton class.
HibernateUtil.java
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static StandardServiceRegistry serviceRegistry;
public static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
Please suggest or provide sample code for this. Thanks.
As suggested I have made the HibernateUtil.java
class as Singleton.
Find the below code, and please suggest / comment to confirm the correctness of code.
Here is the updated code:
public class HibernateUtil {
private static HibernateUtil instance = null;
private static SessionFactory sessionFactory;
private static StandardServiceRegistry serviceRegistry;
private HibernateUtil(){
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
public static HibernateUtil getInstance(){
if(instance == null){
instance = new HibernateUtil();
}
return instance;
}
public synchronized static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Please do correction if the code is not correct, and suggest the correct way.