hibernate学习笔记一-----如何构造Session

这里学习的是hibernate4的构造方式,查看了很多文章了解到这个session的构造在不同的版本是有区别的,在hibernate4以前(至于前到什么地方不太清楚了)可以直接使用Configuration对象的build方法获取到sessionFactory对象。

现在方式不一样了,具体获取代码如下:

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();
    }
}

 

现在需要通过StandardServiceRegistryBuilder对象获取到一个ServiceRegistry对象,然后通过Configuration对象的buildSessionFactory(ServiceRegistry)获取到SessionFactory,然后再调用SessionFactory对象的openSession()方法或者getCurrenSession()获取到session。

你可能感兴趣的:(hibernate)