Hibernate-获取Session的工具类
final public class HibernateUtil {
private static SessionFactory sessionFactory = null;
private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private 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();
threadLocal.set(session);
}
return session;
}
}