Hibernate 的 JNDI 名稱綁定是在 net.sf.hibernate.impl.SessionFactoryObjectFactory 中實現的。以下是詳細調用鏈分析:
Configuration conf = new Configuration().addClass(Cat.class);
SessionFactory sf = conf.buildSessionFactory();
hibernate.properties,屬性保存到 Properties 對象。與 JNDI 相關的關鍵屬性:hibernate.session_factory_name(默認值 hibernate/session_factory)。SessionFactoryImpl 構造器,其中執行:
name = properties.getProperty(Environment.SESSION_FACTORY_NAME);
SessionFactoryObjectFactory.addInstance(uuid, name, this, properties);
Context ctx = NamingHelper.getInitialContext(properties);
NamingHelper.bind(ctx, name, instance);
其中 instance 即 SessionFactory 實例。Hibernate 在 conf.buildSessionFactory() 時,通過一系列類方法調用,將創建的 SessionFactory 實例綁定到配置文件指定的 JNDI 名稱上。Hibernate 具備動態綁定 JNDI 的能力,但前提是必須預先創建 SessionFactory 實例,且該過程必須在所有從 JNDI 獲取 SessionFactory 的程序之前完成。
init() 中執行創建代碼。T3StartupDef)保證預創建。對於任何 App Server,開發者無需關心 JNDI 綁定細節,只需確保 SessionFactory 實例預先創建即可,其餘工作 Hibernate 自動完成。