Struts 2 “完全なHibernate Plugin”とのHibernate統合
最後の
Struts 2 Hibernate integration
の例では、サーブレット・コンテキスト・リスナーを使用してHibernateセッションを再生していましたが、Struts2をHibernateフレームワーク。
しかし、常に改善の余地があります:)このチュートリアルでは、Struts2のプラグイン「http://code.google.com/p/full-hibernate-plugin-for-」を使用してStruts2とHibernateを統合する方法を説明します。 struts2/[Full Hibernate Plugin]”、バージョン2.2GA、http://code.google.com/u/jyoshiriro/[jyoshiriro]で作成されています。
統合手順の概要を参照してください。
-
”
Full Hibernate Plugin
” jarをプロジェクトクラスパスに入れてください. -
注釈「
@ SessionTarget
」を使用してHibernateセッションを挿入します.
”
@ TransactionTarget
“は、Hibernateトランザクションを挿入します。
-
struts.xml
では、パッケージを ”
hibernate-default
“に拡張します.
既定のスタックの代わりに。
関係を参照してください:
Struts 2 <-- (Full Hibernate Plugin) ---> Hibernate <-----> Database
1.プロジェクトの構造
この完全なプロジェクトフォルダ構造を参照してください。
2. MySQLテーブルスクリプト
顧客のテーブルスクリプト。
DROP TABLE IF EXISTS `mkyong`.`customer`; CREATE TABLE `mkyong`.`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 Plugin”と依存関係を取得する
すべてのStruts2、Hibernate、 ”
Full Hibernate Plugin
“とMySQL依存ライブラリを入手してください。 「
Full Hibernate Plugin
」はMavenをサポートしていないため、公式のWebサイトからダウンロードし、手動でMavenローカルリポジトリに組み込む必要があります。
-
ダウンロード
“http://code.google.com/p/full-hibernate-plugin-for-struts2/[Full Hibernate Plugin]”を参照してください。
-
ダウンロードした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
-
それを以下のMaven座標にリンクします.
<依存関係> <groupId> com.google.code </groupId> <artifactId> struts2-fullhibernatecore-plugin </artifactId> <version> 2.2 </version> </dependency>
このチュートリアルのすべての依存関係ライブラリは次のとおりです。
ファイル:pom.xml
….//…
<!– Struts 2 -→
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.1.8</version>
</dependency>
<!-- MySQL database driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency>
<!-- Struts 2 Hibernate Plugins --> <dependency> <groupId>com.google.code</groupId> <artifactId>struts2-fullhibernatecore-plugin</artifactId> <version>2.2</version> </dependency>
<!-- Log4j logging (Struts 2 Hibernate Plugins dependency) --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.9</version> </dependency>
<!-- Hibernate validator (Struts 2 Hibernate Plugins dependency) --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>3.1.0.GA</version> </dependency>
<!-- slf4j logging (Struts 2 Hibernate Plugins dependency) --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency>
<!-- Hibernate core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> <version>3.2.7.ga</version> </dependency>
<!-- Hibernate core library dependency start --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency>
<dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency>
<dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency>
<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency> <!-- Hibernate core library dependency end -->
<!-- Hibernate query library dependency start --> <dependency> <groupId>antlr</groupId> <artifactId>antlr</artifactId> <version>2.7.7</version> </dependency> <!-- Hibernate query library dependency end -->//...
"** Full Hibernate Plugin ** "は** Hibernateバリデータ** と** SLF4j ** 依存関係が必要です。これは、Java開発者の大部分がまだそれを使用していないため、実際には意味がありません。 === 4.休止状態のもの すべてのHibernateモデルと設定用のもの。 ** Customer.java ** - 顧客テーブル用のクラスを作成します。
package com.mkyong.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マッピングファイル。
<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
“http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”>
<!– Generated 20 Julai 2010 11:40:18 AM by Hibernate Tools 3.2.5.Beta -→
<hibernate-mapping>
<class name=”com.mkyong.customer.model.Customer”
table=”customer” catalog=”mkyong”>
<id name=”customerId” type=”java.lang.Long”>
<column name=”CUSTOMER
ID”/>
<generator class=”identity”/>
</id>
<property name=”name” type=”string”>
<column name=”NAME” length=”45″ not-null=”true”/>
</property>
<property name=”address” type=”string”>
<column name=”ADDRESS” not-null=”true”/>
</property>
<property name=”createdDate” type=”timestamp”>
<column name=”CREATED
DATE” length=”19″ not-null=”true”/>
</property>
</class>
</hibernate-mapping>
ファイル:hibernate.cfg.xml、Hibernateデータベース構成ファイル。
<?xml version=”1.0″ encoding=”utf-8″?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD 3.0//EN”
“http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>
<hibernate-configuration>
<session-factory>
<property name=”hibernate.bytecode.use
reflection
optimizer”>false</property>
<property name=”hibernate.connection.password”>password</property>
<property name=”hibernate.connection.url”>jdbc:mysql://localhost:3306/mkyong</property>
<property name=”hibernate.connection.username”>root</property>
<property name=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>
<property name=”show
sql”>true</property>
<property name=”format
sql”>true</property>
<property name=”use
sql
comments”>false</property>
<mapping resource=”com/mkyong/customer/hibernate/Customer.hbm.xml”/>
</session-factory>
</hibernate-configuration>
=== DAO DAOデザインパターンを実装してデータベース操作を実行します。 ** CustomerDAOImpl ** クラスでは、クラスメンバーとしてHibernateセッションとトランザクションの両方を宣言しました。 Struts 2プロジェクトの初期化中、** Full Hibernate Plugin ** は** @ SessionTarget ** と** @ TransactionTarget ** アノテーションをそれぞれ使用して、対応するHibernateセッションとトランザクションをクラスメンバーに注入します。 ** CustomerDAO.java **
package com.mkyong.customer.dao;
import java.util.List;
import com.mkyong.customer.model.Customer;
public interface CustomerDAO{
void addCustomer(Customer customer);
List<Customer> listCustomer();
}
** CustomerDAOImpl.java **
package com.mkyong.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.mkyong.customer.dao.CustomerDAO;
import com.mkyong.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<Customer> listCustomer(){
return session.createQuery("from Customer").list();
}
}
=== 6.アクション Actionクラスでは、DAOクラスを呼び出してデータベース操作を実行します。 ** CustomerAction.java **
package com.mkyong.customer.action;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.mkyong.customer.dao.CustomerDAO;
import com.mkyong.customer.dao.impl.CustomerDAOImpl;
import com.mkyong.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<Customer> customerList = new ArrayList<Customer>(); CustomerDAO customerDAO = new CustomerDAOImpl();
public String execute() throws Exception { return SUCCESS; }
public Object getModel() { return customer; }
public List<Customer> getCustomerList() { return customerList; }
public void setCustomerList(List<Customer> 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” %>
<html>
<head>
</head>
<body>
<h1>Struts 2 Full Hibernate Plugin example</h1>
<h2>Add Customer</h2>
<s:form action=”addCustomerAction” >
<s:textfield name=”name” label=”Name” value=””/>
<s:textarea name=”address” label=”Address” value=”” cols=”50″ rows=”5″/>
<s:submit/>
</s:form>
<h2>All Customers</h2>
<s:if test=”customerList.size() > 0″>
<table border=”1px” cellpadding=”8px”>
<tr>
<th>Customer Id</th>
<th>Name</th>
<th>Address</th>
<th>Created Date</th>
</tr>
<s:iterator value=”customerList” status=”userStatus”>
<tr>
<td><s:property value=”customerId”/></td>
<td><s:property value=”name”/></td>
<td><s:property value=”address”/></td>
<td><s:date name=”createdDate” format=”dd/MM/yyyy”/></td>
</tr>
</s:iterator>
</table>
</s:if>
<br/>
<br/>
</body>
</html>
=== 8. struts.xml Link it all〜make packageは、 "** struts-default ** "の代わりに "** hibernate-default ** "を拡張します。
<?xml version=”1.0″ encoding=”UTF-8″ ?>
<!DOCTYPE struts PUBLIC
“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”
“http://struts.apache.org/dtds/struts-2.0.dtd”>
<struts>
<constant name=”struts.devMode” value=”true”/>
<package name="default" namespace="/" extends="hibernate-default">
<action name="addCustomerAction" class="com.mkyong.customer.action.CustomerAction" method="addCustomer" > <result name="success">pages/customer.jsp</result> </action>
<action name="listCustomerAction" class="com.mkyong.customer.action.CustomerAction" method="listCustomer" > <result name="success">pages/customer.jsp</result> </action>
</package>
</struts>
=== 9.デモ アクセスする: http://localhost:8080/Struts2Example/listCustomerAction.action image://wp-content/uploads/2010/07/Struts2-Full-Hibernate-Plugin-Example1.jpg[Struts 2完全なHibernateプラグインの例、title = "Struts2-Full-Hibernate-Plugin-Example1"、width = 560 、高さ= 480] image://wp-content/uploads/2010/07/Struts2-Full-Hibernate-Plugin-Example2.jpg[Struts 2完全なHibernateプラグインの例、title = "Struts2-Full-Hibernate-Plugin-Example2"、width = 538 、高さ= 480] === ソースコードをダウンロードする それをダウンロードする - link://wp-content/uploads/2010/07/Struts2-Hibernate-FullHibernatePluginExample.zip[Struts2-Hibernate-FullHibernatePluginExample.zip](12 KB) === 参考文献 . http://code.google.com/p/full-hibernate-plugin-for-struts2/[Struts 2 Full Hibernate Plugin documentation]。 link://struts2/struts-2-hibernate-integration-example/[Struts 2 + Hibernate統合の例(サーブレット・コンテキスト・リスナー)]。 link://maven/how-to-include-library-man-in-maven-local-repository/[インストール ライブラリをMavenローカルリポジトリに追加] link://tag/hibernate/[hibernate]link://タグ/integration/[integration]link://tag/struts2/[struts2]