hibernate study notes one ----- how to construct a Session

What I am learning here is the construction method of hibernate4. I have read many articles and learned that the construction of this session is different in different versions. Before hibernate4 (it is not clear where it was before), you can directly use the build method of the Configuration object. Get the sessionFactory object.

Now the way is different, the specific acquisition code is as follows:

package cn.bdx.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
 * Created by Administrator on 2016/5/23.
 */
public class HibernateUtils {

    private static SessionFactory sessionFactory;

    static {
        Configuration configuration = new Configuration().configure();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Session getSession() throws Exception {
        if(sessionFactory == null) {
            throw new Exception("sessionFactory is empty");
        }
        return sessionFactory.openSession();
    }
}

 

Now you need to obtain a ServiceRegistry object through the StandardServiceRegistryBuilder object, then obtain the SessionFactory through the buildSessionFactory (ServiceRegistry) of the Configuration object, and then call the openSession() method or getCurrenSession() of the SessionFactory object to obtain the session.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326629134&siteId=291194637