package com.hkwy.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; public class HibernateUtil{ public static final SessionFactory sessionFactory; static{ Configuration config = new AnnotationConfiguration().configure(); //读取并解析配置文件 sessionFactory = config.buildSessionFactory(); //创建SessionFactory } /** * @return * 打开Session 获取连接 */ public static Session getSession(){ return sessionFactory.openSession(); //打开session } /** * @param session * 关闭session 关闭连接 */ public static void closeSession(Session session){ if(session !=null){ //关闭session session.close(); } } public static void main(String[] args) { System.out.println(HibernateUtil.getSession()); //若连接成功 打印出:SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]]) } }
时间: 2024-11-05 17:27:17