首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Struts PlugIn 整合 Hibernate 實作指南:ThreadLocal Session 與 JNDI 綁定完整範例

     編輯:Java 程式設計入門

五步驟完成 Struts 與 Hibernate 無縫整合

利用 Struts PlugIn 機制,在應用啟動時初始化 Hibernate SessionFactory、綁定 JNDI,請求處理期間透過 ThreadLocal 管理 Session 生命週期,實現標準化整合模式。

步驟 1:建立 HibernateSessionFactory(ThreadLocal 模式)

public class HibernateSessionFactory {
    private static final String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private final ThreadLocal threadLocal = new ThreadLocal();
    private final Configuration cfg = new Configuration();
    private SessionFactory sessionFactory;

    public Session currentSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        if (session == null) {
            if (sessionFactory == null) {
                cfg.configure(CONFIG_FILE_LOCATION);
                sessionFactory = cfg.buildSessionFactory();
            }
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }
        return session;
    }

    public void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);
        if (session != null) session.close();
    }
}

步驟 2:實作 HibernatePlugIn(JNDI 綁定)

public class HibernatePlugin implements PlugIn {
    private HibernateSessionFactory hsf = new HibernateSessionFactory();
    private static final String JNDI_NAME = "jndi_hibernate_factory";

    public void init(ActionServlet servlet, ModuleConfig config) {
        bindFactoryToJNDI(); // 綁定 SessionFactory 到 JNDI
    }

    public void destroy() {
        // 清理資源
    }

    private void bindFactoryToJNDI() {
        try {
            new InitialContext().bind(JNDI_NAME, hsf);
        } catch (Exception e) { e.printStackTrace(); }
    }
}

步驟 3:配置 struts-config.xml

<plug-in className="zy.pro.td.plugin.HibernatePlugin" />
<plug-in className="zy.pro.td.plugin.HibernateSessionFactoryPlugIn" />

步驟 4:建立 ActionForm

標準 ActionForm 實作,包含 username/password 屬性與驗證邏輯。

步驟 5:建立 Action 取得 SessionFactory

Context ctx = new InitialContext();
HibernateSessionFactory hsf = (HibernateSessionFactory) ctx.lookup("jndi_hibernate_factory");
Session session = hsf.currentSession();
// 執行資料庫操作...

整合優勢

  • 生命週期自動化:PlugIn 隨應用啟動/關閉管理資源。
  • ThreadLocal 隔離:每請求獨立 Session,執行緒安全。
  • JNDI 標準查找:Action 透過標準 JNDI 取得工廠,不依賴單例靜態呼叫,利於測試與叢集部署。

此模式為 Struts 1.x 時代整合 Hibernate 的經典最佳實踐,亦為後續 Spring 管理 Hibernate 奠定概念基礎。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved