實作 FactoryBean,getObject() 返回 sessionFactory。afterPropertiesSet() 呼叫 buildSessionFactory() 建構,再以 Proxy 包裝攔截 getCurrentSession()。
Configuration 實例。ThreadLocal Holder 綁定資料源、JTA 事務管理器、LobHandler 供配置期使用。ON_CLOSE、CurrentSessionContext、攔截器、命名策略、型別定義、過濾器定義。configLocations)、屬性 (hibernateProperties)、映射資源 (mappingLocations、cacheableMappingLocations、mappingJarLocations、mappingDirectoryLocations)。postProcessConfiguration() 客製化。config.buildSessionFactory() 生成原始 SessionFactory。schemaUpdate。動態 Proxy 實作 InvocationHandler,攔截 getCurrentSession() 呼叫 SessionFactoryUtils.doGetSession(),其他方法轉發目標 SessionFactory。確保 Spring 事務管理下取得綁定事務的 Session。
TransactionSynchronizationManager (ThreadLocal) 取得 SessionHolder。SpringSessionSynchronization) 實現事務性刷新,調整 FlushMode。FlushMode.NEVER (唯讀) 或 AUTO。allowCreate=false 時)。execute(HibernateCallback, exposeNativeSession) 流程:
getSession() 內部委派 SessionFactoryUtils)。FlushMode、啟用 Filter。action.doInHibernate(session) 執行用戶邏輯。DataAccessException。finally 區塊:既有事務不關閉 Session(由同步器管理);無事務則關閉或註冊延遲關閉。Spring 透過 LocalSessionFactoryBean 統一配置構建 SessionFactory,以動態 Proxy 攔截 getCurrentSession() 實現事務感知 Session 管理,配合 TransactionSynchronizationManager (ThreadLocal) 綁定 Session 生命週期,HibernateTemplate 封裝回調執行與異常轉換,完整解決 Hibernate 整合中的 Session/事務/資源管理難題。