public class HibernateUtil {
private static final SessionFactory sessionFactory;
//使用ThreadLocal管理Session
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
static {
try {
//根据hibernate.cfg.xml建立SessionFactory
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
ex.printStackTrace();
System.err.println("建立SessionFactory错误" + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
session = (sessionFactory != null) ? sessionFactory.openSession(): null;
threadLocal.set(session);
}
return session;
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
}
HibernateUtil工具类
最新推荐文章于 2019-04-26 15:59:31 发布