ThreadLocal

来源:互联网 发布:德州力拓软件 编辑:程序博客网 时间:2024/06/09 22:51
package main.cn.happy.entity.cn.hql02.hql.util;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;/** * Created by lenovo on 2017/10/6. */public class hibernateUtil {    static ThreadLocal<Session> tlSession;    static Configuration cfg;    static SessionFactory sessionFactory;    // 静态代码块    static {        //创建configure 对象        cfg = new Configuration().configure();        //        sessionFactory = cfg.buildSessionFactory();        tlSession = new ThreadLocal<Session>();    }    public static Session getSession() {        Session session = tlSession.get();        if (session == null) {            session = sessionFactory.openSession();            tlSession.set(session);        }        return session;    }    // 关闭    public void Close() {        Session session = tlSession.get();        if (session != null) {            session.close();            tlSession.set(null);        }    }

}

------------------------------------------------------

package main.cn.happy.entity.cn.hql02.hql.util;import org.hibernate.Session;/** * Created by lenovo on 2017/10/6. */public class MyThread extends Thread {    @Override    public void run() {        Session session = hibernateUtil.getSession();        Session session2 = hibernateUtil.getSession();        System.out.println(" 子线程=== 1  " + session.hashCode());        System.out.println("    子线程===  2 " + session2.hashCode());    }}


原创粉丝点击