Hibernate 提供session的工具类HibernateUtils

package cn.itcast.utils;

import java.sql.Connection;
import java.sql.SQLException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.jdbc.Work;

public class HibernateUtils {
    
    private static Configuration cfg;
    private static SessionFactory sessionFactory;
    private static ThreadLocal<Session> threadLocal;
    
    static {
        cfg = new Configuration();//一个加载器
        cfg.configure();//加载默认位置核心配置文件
        sessionFactory = cfg.buildSessionFactory();//一个session工厂
        threadLocal=new ThreadLocal<Session>();
    }

    
    public static Session getSession() {
        
        Session session=threadLocal.get();
        if(session==null) {
            
            session = sessionFactory.openSession();//创建session
            threadLocal.set(session);
            session=threadLocal.get();
        }
        return session;
    }
    
    public static void main(String[] args) {
        Session session = getSession();
        session.doWork(new Work() {

            @Override
            public void execute(Connection con) throws SQLException {
                // TODO Auto-generated method stub
                System.out.println(con);
                
            }});
    }
}

 

posted @ 2018-05-09 18:26  Advancing-Swift  阅读(251)  评论(0编辑  收藏  举报