鍍金池/ 教程/ Java/ Struts2 + Hibernate使用“Full Hibernate Plugin"插件集成
設置復選框的默認值
<s:if>, <s:elseIf>, <s:else> 標簽示例
下拉框示例
Struts2 &lt;s:bean&gt;標簽示例
Struts2 &lt;s:date&gt;標簽示例
<s:text>標簽示例
Struts2的ActionError&ActionMessage示例
Struts2 MySQL數(shù)據(jù)庫訪問
Struts2上傳多個文件例子
Struts2+Log4j集成
Struts 2 hello world (XML版本)
Struts2和Spring集成
Struts2 控件標簽
Struts2 和 JSON 實例
Struts2 環(huán)境配置
Struts2 &lt;s:checkboxlist&gt;多個復選框例子
Struts2 注釋類型
在Struts2中配置靜態(tài)參數(shù)
Struts2 驗證框架
Struts2 param 標簽
Struts2 &lt;s:hidden&gt;隱藏值例子
Struts2下載文件實例
Struts2 &lt;sx:autocompleter&gt;自動提示例子
Struts2 action標簽
autocompleter自動完成示例
Struts2 merge標簽
Struts2 &lt;s:action&gt;標簽示例
<s:property>標簽示例
Struts2 &lt;s:sort&gt;標簽示例
Struts2和Hibernate集成
自動選擇下拉框示例
Struts2 結果和結果類型
Struts2 是什么?
如何刪除Struts2動作的后綴擴展名
Struts2 Hello World 實例
<s:action>標簽示例
<s:bean>標簽示例
Struts2 + Quartz調度集成實例
如何獲取ServletContext對象
Struts2 &lt;s:i18n&gt;標簽示例
Struts2 append標簽
i18n 或本地化示例
autocompleter + JSON 示例
Struts2獲取HttpServletRequest實例
updownselect 示例
Struts2 &lt;s:debug&gt;標簽示例
Struts2重寫攔截器參數(shù)
多個Struts配置文件示例
<s:i18n>標簽示例
Struts2中文本地化問題
文件上傳示例
Struts2 &lt;s:property&gt;標簽實例
Struts2攔截器棧的例子
<s:merge>標簽示例
Struts2 數(shù)據(jù)標簽
Struts2 &lt;s:merge&gt;標簽示例
復選框checkboxes 示例
Struts2 generator標簽
如何配置Struts2全局資源包
key 屬性示例
Struts2 注釋
FilterDispatcher 和 StrutsPrepareAndExecuteFilter區(qū)別?
Struts 2 Hello World (注解版本)
Struts 2 + Log4j 集成實例
Struts2 值棧/OGNL
Struts2配置Action類的靜態(tài)參數(shù)
Struts2 本地化/國際化(i18n)
Chinese 本地化問題
Struts2單選預選按鈕值
Struts2 include標簽
Struts2 + Hibernate 集成實例
配置全局資源包
Struts2 異常處理
Struts2 &lt;s:set&gt;標簽示例
Struts2 &lt;s:doubleselect&gt;示例
Struts2 iterator標簽
optiontransferselect 示例
Struts2映射攔截動作
head 示例
Struts2+Hibernate使用Full Hibernate Plugin集成
Struts2命名空間配置和解釋
<s:param>標簽示例
Struts2+Hibernate集成實例
Struts2 &lt;s:head&gt;示例
Struts2 &lt;s:push&gt;標簽示例
Struts2文件上傳例子
Struts2 &lt;s:param&gt;標簽示例
@ResultPath 注釋示例
Struts2 體系結構
Struts2 execAndWait攔截器例子
Struts2 攔截器
Textarea - 文本域
Struts2教程
<s:push>標簽示例
Struts2 文件上傳
Struts2 date 標簽
Struts2 &lt;s:texttag&gt;標簽示例
Struts2+Quartz2調度集成實例
Struts2開發(fā)模式
Struts2 autocompleter+JSON例子
Struts2 類型轉換
<s:url>標簽示例
Struts2 Ajax 標簽
Struts2 bean 標簽
<s:iterator>標簽迭代示例
Hidden隱藏值示例
在Struts2獲取HttpServletResponse對象
Struts2 主題和模板
Struts2自動選擇下拉框的值
Struts2下載文件實例
在Struts2中獲取 HttpServletRequest
級聯(lián)選擇示例
Struts2 &lt;sx:datetimepicker&gt;示例
Struts2 include(包含)多個配置文件
Struts2 &lt;s:select&gt;下拉框例子
Struts2 Action/動作
Struts2 &lt;s:textarea&gt;文本域實例
Struts2+Spring集成實例
Struts2 &lt;s:updownselect&gt;示例
Struts2 property 標簽
Struts2 &lt;s:url&gt;標簽示例
Struts2 表單標簽
Struts2資源包使用示例
subset tag example
Struts 2 ActionError &amp; ActionMessage Example
Struts2 MVC架構
Struts2 if/else標簽
Struts2 &lt;s:generator&gt;標簽示例
<s:include>標簽示例
Struts2開發(fā)者模式
<s:generator> 標簽示例
復選框heckbox 示例
Struts2 text 標簽
Radio 單選按鍵示例
Struts2 &lt;s:a&gt;標簽示例
Struts2 key鍵屬性示例
Struts2設置多個復選框缺省值
Struts2 基于XML校驗
Struts2 配置文件
Struts2 &lt;s:radio&gt;單選按鈕例子
Struts2 發(fā)送郵件Email
Struts2獲取HttpServletResponse實例
<s:sort>標簽示例
Struts2 &lt;s:optiontransferselect&gt;示例
Struts2和Tiles集成
Struts2模型驅動實例
Struts2的FilterDispatcher和StrutsPrepareAndExecuteFilter有什么不同?
<s:append>標簽示例
組合框示例
Struts2 &lt;s:password&gt;密碼示例
datetimepicker 日期選擇
Struts2 &lt;s:iterator&gt;迭代器標簽示例
TextBox文檔示例
Struts2 url標簽
資源包使用示例
Struts2本地化和國際化
Struts2 &lt;s:subset&gt;標簽示例
Struts2 + Hibernate使用“Full Hibernate Plugin"插件集成
Struts2和JSON實例
Struts2注解示例
Struts2 &lt;s:checkbox&gt;復選框例子
Struts2快速入門
<s:date>標簽示例
Struts2 set 標簽
<s:set>標簽示例
Struts2 命名空間配置和解釋
Struts 2 hello world (XML版本)
&nbsp;預選單選按鈕
<s:a>標簽示例
Struts2+Spring+Hibernate集成實例
Struts2 &lt;s:combobox&gt;組合框的例子
Struts2 if,elseif,else標簽示例
Struts2 @ResultPath注釋示例
struts2 &lt;s:append&gt;標簽示例
Struts2 &lt;s:textfield&gt;文本示例
多文件上傳示例
使用Struts2動作
<s:debug>標簽示例
在Struts2中如何獲取ServletContext對象
Struts2 &lt;s:include&gt;標簽示例
Password 示例

Struts2 + Hibernate使用“Full Hibernate Plugin"插件集成

在上篇 Struts2 + Hibernate集成 實例中, 它使用 servlet 上下文監(jiān)聽 Hibernate 的 Session,而且把Struts2和Hibernate框架集成。

但是,總有一些東西要提高。在本教程中,我們將展示如何整合Struts2+Hibernate,并使用Struts2一個名為“Full Hibernate Plugin“的插件。

見下面的集成步驟:
  1. 把 “Full Hibernate Plugin” jar 放入到工程類路徑。
  2. 使用 “@SessionTarget” 注釋來注入到 Hibernate session; 當“@TransactionTarget” 注釋注入到Hibernate 事務。
  3. 在 struts.xml, 讓包擴展 “hibernate-default“,而不是默認的堆棧。

看看下面的關系:

Struts 2 <-- (Full Hibernate Plugin) ---> Hibernate <-----> Database
注,
本教程是從以前的 Struts2 + Hibernate集成 實例(servlet context listener)更新版本。因此,JSP 和 Hibernate 配置基本相同,只是整合的部分是有點不同,嘗試比較既能發(fā)現(xiàn)不同。

1. 工程結構

在節(jié)教程,我們創(chuàng)建一個工程名為 full-hibernate 的web工程??纯催@個項目文件夾的完整結構。

2. MySQL創(chuàng)建表腳本

Customer表結構

CREATE TABLE `customer` (
  `customer_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  `address` varchar(255) NOT NULL,
  `create_date` datetime NOT NULL,
  PRIMARY KEY (`customer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

3. Hibernate相關配置

所有 Hibernate 的模型和配置的東西。

Customer.java – 為customer 表創(chuàng)建一個類。

package com.yiibai.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 的 customer 表映射。

<?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.yiibai.customer.model.Customer" 
		table="customer" catalog="yiibai">
        <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 數(shù)據(jù)庫配置

<?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/yiibai</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/yiibai/customer/hibernate/Customer.hbm.xml" />
  </session-factory>
</hibernate-configuration>

5. DAO

實現(xiàn)DAO設計模式執(zhí)行數(shù)據(jù)庫操作。在 CustomerDAOImpl 類, 聲明Hibernate會話和事務為類成員。在Struts 2的項目初始化, “Full Hibernate Plugin” 使用 @SessionTarget 和 @TransactionTarget 分別標注將注入相應的 Hibernate 會話和事務成為類成員。

CustomerDAO.java

package com.yiibai.customer.dao;

import java.util.List;

import com.yiibai.customer.model.Customer;
 
public interface CustomerDAO{
	
	void addCustomer(Customer customer);
	
	List<Customer> listCustomer();
	
}

CustomerDAOImpl.java

package com.yiibai.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.yiibai.customer.dao.CustomerDAO;
import com.yiibai.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

在Action類,調用DAO類來執(zhí)行數(shù)據(jù)庫操作。

CustomerAction.java

package com.yiibai.customer.action;

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

import com.yiibai.customer.dao.CustomerDAO;
import com.yiibai.customer.dao.impl.CustomerDAOImpl;
import com.yiibai.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

鏈接所有?讓包擴展 “hibernate-default” 來代替 “struts-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.yiibai.customer.action.CustomerAction" method="addCustomer" >
       <result name="success">pages/customer.jsp</result>
    </action>
	
    <action name="listCustomerAction" 
	class="com.yiibai.customer.action.CustomerAction" method="listCustomer" >
        <result name="success">pages/customer.jsp</result>
    </action>
		
</package>	
</struts>

9. 實例

訪問以下網(wǎng)址 : http://localhost:8080/full-hibernate/addCustomerAction.action

參考

  1. Struts2 Full Hibernate插件文檔
  2. Struts2 + Hibernate集成實例
  3. 安裝庫到Maven本地資源庫

下載代碼

下載所有源代碼 – http://pan.baidu.com/s/1o6tjSam