Struts 2のHibernate統合の例
それをダウンロードする –
Struts2-Hibernate-Integration-Example.zip
Struts2には、Hibernateフレームワークを統合するための公式のプラグインはありません。ただし、次の手順で対処できます。
-
カスタム
ServletContextListener
を登録してください. -
ServletContextListener
クラスで、** Hibernateを初期化します
サーブレットのコンテキスト** に格納します。
-
アクションクラスでは、
Hibernateセッションをサーブレットコンテキスト
から取得し、
通常どおりHibernateタスクを実行します。
関係を参照してください:
Struts 2 <-- (Servlet Context) ---> Hibernate <-----> Database
このチュートリアルでは、
Struts 2
で開発された単純な顧客モジュール(追加機能とリスト機能)を示し、
Hibernate
でデータベース操作を実行します。統合部分は上記のメカニズムを使用しています(サーブレットコンテキストでHibernateセッションを格納して取得します)。
この回避策は、古典的なリンク://struts/struts-hibernate-integration-example/[Struts 1.xとHibernate integration]と非常によく似ていますが、古典的なStruts 1.xはStrutsのプラグインを使用しています。一方、Struts 2は汎用サーブレット・リスナーを使用しています。
1.プロジェクトの構造
この完全なプロジェクトフォルダ構造を参照してください。
2. MySQLテーブルスクリプト
デモ用の顧客テーブルを作成します。ここにSQLテーブルスクリプトがあります。
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.依存関係
Struts2、Hibernate、およびMySQLの依存関係ライブラリを入手してください。
….//…
<!– 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>
<!-- 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 -->//...
=== 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”>
<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>
=== 5. Hibernate ServletContextListener ** ServletContextListener ** を作成し、** Hibernateセッションを初期化してサーブレットコンテキスト** に格納します。 ** HibernateListener .java **
package com.mkyong.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 **
<!DOCTYPE web-app PUBLIC
“-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN”
“http://java.sun.com/dtd/web-app
2
3.dtd” >
<web-app>
<display-name>Struts 2 Web Application</display-name>
<filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter>
<filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/** </url-pattern> </filter-mapping>
<listener> <listener-class> com.mkyong.listener.HibernateListener </listener-class> </listener>
</web-app>
=== 6.アクション Actionクラスでは、** サーブレットコンテキスト** からHibernateセッションを取得し、通常どおりにHibernateタスクを実行します。 ** CustomerAction.java **
package com.mkyong.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.mkyong.customer.model.Customer;
import com.mkyong.listener.HibernateListener;
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>();
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{
//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” %>
<html>
<head>
</head>
<body>
<h1>Struts 2 + Hibernate integration 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 すべてのリンク〜
<?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="struts-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-Hibernate-AddCustomer.jpg[Struts 2 Hibernate Add Customer、title = "Struts2-Hibernate-AddCustomer"、width = 640、height = 400] 名前と住所の欄に記入し、送信ボタンを押すと、挿入された顧客の詳細がすぐに一覧表示されます。 image://wp-content/uploads/2010/07/Struts2-Hibernate-ListCustomer.jpg[Struts2 Hibernate List Customer、title = "Struts2-Hibernate-ListCustomer"、width = 638、height = 480] === リファレンス . link://struts2/struts-2-hibernate-integration-with-full-hibernate-plugin/[Struts 2完全なHibernate PluginとのHibernate統合 。 http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener.html[ServletContextListener ドキュメンテーション]。リンク://struts/struts-hibernate-integration-example/[Struts Hibernate 統合例] link://tag/hibernate/[hibernate]link://タグ/integration/[integration]link://tag/struts2/[struts2]