public class HibernateUtil {
private static Log log=LogFactory.getLog(HibernateUtil.class);
private static final SessionFactory sessionFactory;
static {
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
log.error("Initial SessionFactory creation failed.",ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session=new ThreadLocal();
//得到session
public static Session Session() throws HibernateException {
Session s=(Session)session.get();
//Open a new Session, if this Thread has none yet
if (s==null) {
s=sessionFactory.openSession();
session.set(s);
}
return s;
}
//关闭session
public static void closeSession() throws HibernateException {
Session s=(Session) session.get();
session.set(null);
if (s !=null)
s.close();
}
}
HibernateUtil类(操作数据源 session 的管理)
最新推荐文章于 2021-01-30 11:12:25 发布