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=[]]) } }