我是Java的Hibernate框架的新手。
我有一个HibernateUtil
类的代码,我不知道INSTANCE
的来源。
它具有HibernateUtil
类的作用,如何???
代码是这样的...
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;
}
}
最佳答案
HibernateUtil正在实现单例模式:该类只能有一个实例,并且该实例是HibernateUtil.INSTANCE。