什么是HibernateUtil中的INSTANCE?

时间:2014-01-23 10:00:16

标签: java hibernate instance

我是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;
}
}

2 个答案:

答案 0 :(得分:2)

HibernateUtil正在实现单例模式:该类只能有一个实例,该实例是HibernateUtil.INSTANCE。

答案 1 :(得分:0)

Java中的enum实际上是一个类。一个隐含地延伸java.lang.Enum。您在INSTANCE看到的特殊语法;是枚举常量的声明。这将用于创建一个可以在代码中引用的枚举类的实例。