Struts 2のHibernate統合の例

Struts 2 + Hibernate統合の例

ダウンロード–Struts2-Hibernate-Integration-Example.zip

Struts2には、Hibernateフレームワークを統合するための公式プラグインはありません。 ただし、次の手順で回避できます。

  1. カスタムServletContextListenerを登録します。

  2. ServletContextListenerクラスで、Hibernate session and store it into the servlet contextを初期化します。

  3. アクションクラスget the Hibernate session from the servlet contextで、通常どおりHibernateタスクを実行します。

関係を参照してください。

Struts 2 <-- (Servlet Context) ---> Hibernate <-----> Database

このチュートリアルでは、Struts 2で開発された単純な顧客モジュール(追加およびリスト機能)を示し、Hibernateを使用してデータベース操作を実行します。 統合部分は上記のメカニズムを使用しています(サーブレットコンテキストでHibernateセッションを保存および取得します)。

この回避策は、従来のStruts 1.x and Hibernate integrationと非常によく似ており、従来のStruts1.xがStrutsのプラグインを使用しているだけです。 Struts2が汎用サーブレットリスナーを使用している間。

1. プロジェクト構造

このプロジェクトフォルダ構造全体をご覧ください。

Struts 2 Hibernate integration example

2. MySQLテーブルスクリプト

デモ用の顧客テーブルを作成します。 これがSQLテーブルスクリプトです。

DROP TABLE IF EXISTS `example`.`customer`;
CREATE TABLE  `example`.`customer` (
  `CUSTOMER_ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) NOT NULL,
  `ADDRESS` varchar(255) NOT NULL,
  `CREATED_DATE` datetime NOT NULL,
  PRIMARY KEY (`CUSTOMER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

3. 依存

Struts2、Hibernate、およびMySQL依存ライブラリを入手してください。

//...
    
    
            org.apache.struts
        struts2-core
        2.1.8
        

    
    
        mysql
        mysql-connector-java
        5.1.9
    

    
    
        org.hibernate
        hibernate
        3.2.7.ga
    

    
    
        dom4j
        dom4j
        1.6.1
    

    
        commons-logging
        commons-logging
        1.1.1
    

    
        commons-collections
        commons-collections
        3.2.1
    

    
        cglib
        cglib
        2.2
    
    

    
    
        antlr
        antlr
        2.7.7
    
    
//...

4. 休止状態のもの

Hibernateモデルおよび構成スタッフ。

Customer.java –顧客テーブルのクラスを作成します。

package com.example.customer.model;

import java.util.Date;

public class Customer implements java.io.Serializable {

    private Long customerId;
    private String name;
    private String address;
    private Date createdDate;

    //getter and setter methods
}

Customer.hbm.xml –顧客用のHibernateマッピングファイル。



    

        
            
            
        
        
            
        
        
            
        
        
            
        
    

hibernate.cfg.xml –Hibernateデータベース構成ファイル。



  
    false
    password
    jdbc:mysql://localhost:3306/example
    root
    org.hibernate.dialect.MySQLDialect
    true
    true
    false
    
  

5. Hibernate ServletContextListener

ServletContextListenerを作成し、Hibernate session and store it into the servlet contextを初期化します。

HibernateListener .java

package com.example.listener;

import java.net.URL;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateListener implements ServletContextListener{

    private Configuration config;
    private SessionFactory factory;
    private String path = "/hibernate.cfg.xml";
    private static Class clazz = HibernateListener.class;

    public static final String KEY_NAME = clazz.getName();

    public void contextDestroyed(ServletContextEvent event) {
      //
    }

    public void contextInitialized(ServletContextEvent event) {

     try {
            URL url = HibernateListener.class.getResource(path);
            config = new Configuration().configure(url);
            factory = config.buildSessionFactory();

            //save the Hibernate session factory into serlvet context
            event.getServletContext().setAttribute(KEY_NAME, factory);
      } catch (Exception e) {
             System.out.println(e.getMessage());
       }
    }
}

web.xmlファイルにリスナーを登録します。
web.xml




  Struts 2 Web Application

  
    struts2
    
      org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    
  

  
    struts2
    /*
  

  
    
      com.example.listener.HibernateListener
    
  

6. アクション

Actionクラスで、get the Hibernate session from the servlet contextを実行し、通常どおりHibernateタスクを実行します。

CustomerAction.java

package com.example.customer.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.example.customer.model.Customer;
import com.example.listener.HibernateListener;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class CustomerAction extends ActionSupport
    implements ModelDriven{

    Customer customer = new Customer();
    List customerList = new ArrayList();

    public String execute() throws Exception {
        return SUCCESS;
    }

    public Object getModel() {
        return customer;
    }

    public List getCustomerList() {
        return customerList;
    }

    public void setCustomerList(List customerList) {
        this.customerList = customerList;
    }

    //save customer
    public String addCustomer() throws Exception{

        //get hibernate session from the servlet context
        SessionFactory sessionFactory =
             (SessionFactory) ServletActionContext.getServletContext()
                     .getAttribute(HibernateListener.KEY_NAME);

        Session session = sessionFactory.openSession();

        //save it
        customer.setCreatedDate(new Date());

        session.beginTransaction();
        session.save(customer);
        session.getTransaction().commit();

        //reload the customer list
        customerList = null;
        customerList = session.createQuery("from Customer").list();

        return SUCCESS;

    }

    //list all customers
    public String listCustomer() throws Exception{

        //get hibernate session from the servlet context
        SessionFactory sessionFactory =
             (SessionFactory) ServletActionContext.getServletContext()
                     .getAttribute(HibernateListener.KEY_NAME);

        Session session = sessionFactory.openSession();

        customerList = session.createQuery("from Customer").list();

        return SUCCESS;

    }
}

7. JSPページ

顧客を追加およびリストするJSPページ。

customer.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>





Struts 2 + Hibernate integration example

Add Customer

All Customers

Customer Id Name Address Created Date


8. struts.xml

それをすべてリンクしてください〜




  

  

    
       pages/customer.jsp
    

    
        pages/customer.jsp
    

  

9. Demo

カスタマーモジュールにアクセス:http://localhost:8080/Struts2Example/listCustomerAction.action

Struts 2 Hibernate Add Customer

名前と住所のフィールドに入力し、送信ボタンを押すと、挿入された顧客の詳細がすぐにリストされます。

Struts2 Hibernate List Customer