package com.yyy.util;
//import org.hibernate.Session;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
final public class HibernateUtil {
private static SessionFactory sessionFactory = null;
private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
public HibernateUtil(){
}
static{
sessionFactory = new Configuration().configure().buildSessionFactory();
}
//获取全新的session
public static Session openSession(){
return sessionFactory.openSession();
}
//获取和线程关联的session
public static Session getCurrentSession(){
Session session = threadLocal.get();
//判断是否得到
if(session == null){
session = sessionFactory.openSession();
//session对象设置到threadLocal -- 相当于session和线程绑定
threadLocal.set(session);
}
return session;
}
//import org.hibernate.Session;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
final public class HibernateUtil {
private static SessionFactory sessionFactory = null;
private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
public HibernateUtil(){
}
static{
sessionFactory = new Configuration().configure().buildSessionFactory();
}
//获取全新的session
public static Session openSession(){
return sessionFactory.openSession();
}
//获取和线程关联的session
public static Session getCurrentSession(){
Session session = threadLocal.get();
//判断是否得到
if(session == null){
session = sessionFactory.openSession();
//session对象设置到threadLocal -- 相当于session和线程绑定
threadLocal.set(session);
}
return session;
}
}
MySessionFactory
package com.yyy.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
//使用hibernate请保证只有一个SessionFactory(一个数据库)
final public class MySessionFactory {
private static SessionFactory sessionFactory = null;
//1创建configuration对象
// Configuration configuration = new Configuration().configure();
//2 //2.创建会话工厂、SessionFactory》》重量级对象。
// SessionFactory sessionFactory = configuration.buildSessionFactory();
public MySessionFactory(){
}
static {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
public static SessionFactory getsessionFactory(){
return sessionFactory;
}
}