Reputation: 4525
I am new to Hibernate framework of Java.
I have a code of HibernateUtil
class, I didn't understand from where the INSTANCE
came.
It holds the onstance of HibernateUtil
class, how???
The code is this...
import java.util.Properties;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public enum HibernateUtil {
INSTANCE; // what about this???
public static SessionFactory sessionFactory = null;
private synchronized SessionFactory initialiseSessionFactory() {
if (sessionFactory == null) {
Configuration config = new Configuration();
config.addAnnotatedClass(demo1.class);
config.addAnnotatedClass(demo2.class);
config.configure();
//get the properties from Hibernate configuration file
Properties configProperties = config.getProperties();
ServiceRegistryBuilder serviceRegisteryBuilder = new ServiceRegistryBuilder();
ServiceRegistry serviceRegistry = serviceRegisteryBuilder.applySettings(configProperties).buildServiceRegistry();
sessionFactory = config.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}
public Session getSession() {
Session hibernateSession = null;
if (sessionFactory == null) {
hibernateSession = initialiseSessionFactory().openSession();
} else {
hibernateSession = sessionFactory.openSession();
}
return hibernateSession;
}
}
Upvotes: 1
Views: 640
Reputation: 2171
An enum
in Java is actually a class. One that implicitly extends java.lang.Enum
. The special syntax you see at INSTANCE
; is a declaration of an enum constant. This is going to be used to make an instance of your enum class which can be referred to in code.
Upvotes: 0
Reputation: 32831
HibernateUtil is implementing the singleton pattern: there can be only one instance of that class, and that instance is HibernateUtil.INSTANCE.
Upvotes: 2