欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Hibernate 提供session的工具类HibernateUtils

程序员文章站 2022-10-04 16:22:58
package cn.itcast.utils; import java.sql.Connection; import java.sql.SQLException; import org.hibernate.Session; import org.hibernate.SessionFactory; ... ......
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) {
            cfg.configure();//加载默认核心配置文件
            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);
                
            }});
    }
}