許多 Java 初學者容易混淆 javax.servlet.http.HttpSession 與 org.hibernate.Session,兩者雖同名但職責截然不同。
HttpSession session = request.getSession();session.invalidate() 主動銷毀。Session session = HibernateSessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// 業務操作,可能調用多個 DAO 方法
dao.update(entity1, session);
dao.update(entity2, session);
tx.commit();
} catch (Exception e) {
if (tx != null) tx.rollback();
throw e;
} finally {
HibernateSessionFactory.closeSession(session); // 確保關閉
}
finally 區塊或 Spring 的 OpenSessionInViewFilter 保證 Session 必被關閉。理解這兩者的本質區別,是避免記憶體洩漏、資料不一致等低級錯誤的關鍵。