Struts 2 "完全なHibernate Plugin"とのHibernate統合

Struts 2 + Hibernateと「フルHibernateプラグイン」の統合

最後のStruts 2 + Hibernate integrationの例では、サーブレットコンテキストリスナーを使用してHibernateセッションを操作し、Struts2をHibernateフレームワークと統合することは非常にうまくいきました。

ただし、常に改善すべき点があります:)このチュートリアルでは、「http://code.google.com/p/full-hibernate-plugin-for-」という名前のStruts2のプラグインを使用してStruts2とHibernateを統合する方法を示します。 struts2 / [Full Hibernate Plugin]“、バージョン2.2GA、jyoshiriroによって作成されました。

統合手順の概要を参照してください。

  1. Full Hibernate Plugin」jarをプロジェクトクラスパスに配置します。

  2. アノテーション「@SessionTarget」を使用してHibernateセッションを挿入します。 「@TransactionTarget」はHibernateトランザクションを注入します。

  3. struts.xmlで、デフォルトのスタックの代わりに、パッケージが「hibernate-default」を拡張するようにします。

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

Struts 2 <-- (Full Hibernate Plugin) ---> Hibernate <-----> Database

Note
このチュートリアルは、前のStruts 2 + Hibernate integrationの例(サーブレットコンテキストリスナー)からの更新バージョンです。したがって、JSPとHibernateの構成はほぼ同じですが、統合部分が少し異なります。両方を比較して、違いを見つけてください。

1. プロジェクト構造

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

Struts 2 Hibernate plugin folder structure

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

顧客のテーブルスクリプト。

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. 「フルHibernateプラグイン」と依存関係を取得

すべてのStruts2、Hibernate、「Full Hibernate Plugin」、およびMySQL依存関係ライブラリを取得します。 「Full Hibernate Plugin」はMavenをサポートしていないため、公式Webサイトからダウンロードして、Mavenローカルリポジトリに手動で含める必要があります。

  1. 「http://code.google.com/p/full-hibernate-plugin-for-struts2/ [完全なHibernateプラグイン]」をダウンロードします。

  2. ダウンロードしたjarをc:ドライブに入れ、次のMavenのコマンドを使用してMavenローカルリポジトリに含めます。

    mvn install:install-file -Dfile=c:\struts2-fullhibernatecore-plugin-2.2-GA.jar
    -DgroupId=com.google.code -DartifactId=struts2-fullhibernatecore-plugin
    -Dversion=2.2 -Dpackaging=jar
  3. それをフォローMaven座標にリンクします。

            
            com.google.code
            struts2-fullhibernatecore-plugin
            2.2
        

このチュートリアルのすべての依存ライブラリは次のとおりです。

ファイル:pom.xml

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

    
    
        mysql
        mysql-connector-java
        5.1.9
    

    
    
        com.google.code
        struts2-fullhibernatecore-plugin
        2.2
    

    
    
                log4j
            log4j
            1.2.9
        

    
    
               org.hibernate
           hibernate-validator
           3.1.0.GA
        

    
    
               org.slf4j
           slf4j-api
           1.6.1
        

    
    
        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
    
    
//...

Full Hibernate Plugin」にはHibernate validatorSLF4jの依存関係が必要ですが、ほとんどのJava開発者はまだそれを使用していないため、実際には意味がありません。

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. DAO

データベース操作を実行するDAO設計パターンを実装します。 CustomerDAOImplクラスで、Hibernateセッションとトランザクションの両方をクラスメンバーとして宣言しました。 Struts 2プロジェクトの初期化中に、「Full Hibernate Plugin」は、対応するHibernateセッションとトランザクションをそれぞれ@SessionTarget@TransactionTargetアノテーションを使用してクラスメンバーに挿入します。

CustomerDAO.java

package com.example.customer.dao;

import java.util.List;

import com.example.customer.model.Customer;

public interface CustomerDAO{

    void addCustomer(Customer customer);

    List listCustomer();

}

CustomerDAOImpl.java

package com.example.customer.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.example.customer.dao.CustomerDAO;
import com.example.customer.model.Customer;

public class CustomerDAOImpl implements CustomerDAO{

    @SessionTarget
    Session session;

    @TransactionTarget
    Transaction transaction;

    //add the customer
    public void addCustomer(Customer customer){

        session.save(customer);

    }

    //return all the customers in list
    public List listCustomer(){

        return session.createQuery("from Customer").list();

    }

}

6. アクション

Actionクラスで、DAOクラスを呼び出してデータベース操作を実行します。

CustomerAction.java

package com.example.customer.action;

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

import com.example.customer.dao.CustomerDAO;
import com.example.customer.dao.impl.CustomerDAOImpl;
import com.example.customer.model.Customer;
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();
    CustomerDAO customerDAO = new CustomerDAOImpl();

    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{

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

        //reload the customer list
        customerList = null;
        customerList = customerDAO.listCustomer();

        return SUCCESS;

    }

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

        customerList = customerDAO.listCustomer();

        return SUCCESS;

    }

}

7. JSPページ

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

customer.jsp

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





Struts 2 Full Hibernate Plugin example

Add Customer

All Customers

Customer Id Name Address Created Date


8. struts.xml

すべてをリンクする〜makeパッケージは、「struts-default」ではなく「hibernate-default」を拡張します。




  

  

    
       pages/customer.jsp
    

    
        pages/customer.jsp
    


ソースコードをダウンロード

ダウンロード–Struts2-Hibernate-FullHibernatePluginExample.zip(12 KB)