Struts 2 + Hibernate “完整Hibernate插件”方式集成

本文介绍如何使用Struts2的FullHibernatePlugin插件来整合Struts2与Hibernate框架,通过示例展示如何配置项目、设置依赖库、实现DAO模式等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Download it – Struts2-Hibernate-FullHibernatePluginExample.zip (12 KB)

In last Struts 2 + Hibernate integration example, it use the servlet context listener to play around with the Hibernate session, and it did very well to integrate Struts2 with Hibernate framework.

But, there is always something to improve :) In this tutorial, we show you how to integrate Struts2 and Hibernate by using a Struts2′s plugin named “Full Hibernate Plugin“, version 2.2GA, created by jyoshiriro.

See the summary of integration steps :

  1. Put the “Full Hibernate Plugin” jar in the project class path.
  2. Use annotations “@SessionTarget” to inject the Hibernate session; While “@TransactionTarget” to inject the Hibernate transaction.
  3. In struts.xml, make the package extends “hibernate-default“, instead of the default stack.

See the relationship :

Struts 2 <-- (Full Hibernate Plugin) ---> Hibernate <-----> Database
Note
This tutorial is an update version from the previous  Struts 2 + Hibernate integration example (servlet context listener), So the JSP and Hibernate configuration are almost same, just the integration part is a bit different, try to compare both to spot the different.
1. Project structure

See this full project folder structure.

Struts 2 Hibernate plugin folder structure
2. MySQL table script

Customer’s table script.

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. Get “Full Hibernate Plugin” and Dependencies

Get all the Struts2, Hibernate, “Full Hibernate Plugin” and MySQL dependency libraries. Since the “Full Hibernate Plugin” is not support Maven, you need to download it from the official website and include into your Maven local repository manually.

  1. Download “Full Hibernate Plugin“.
  2. Put the downloaded jar into c: drive and use following Maven’s command to include it into Maven local repository.
    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. Link it with the follow Maven coordinate.
            <dependency>
    		<groupId>com.google.code</groupId>
    		<artifactId>struts2-fullhibernatecore-plugin</artifactId>
    		<version>2.2</version>
    	</dependency>

Here’s all the dependency libraries in this tutorial :

File : 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 -->
//...
The “ Full Hibernate Plugin” is required the  Hibernate validator and  SLF4j dependency, which is not really make sense, as most of the Java developers still do not use it.
4. Hibernate Stuff

All the Hibernate models and configuration stuff.

Customer.java – Create a class for customer table.

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 mapping file for 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.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>

File : hibernate.cfg.xml, Hibernate database configuration file.

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

Implements DAO design pattern to perform the database operation. In the CustomerDAOImpl class, declared both Hibernate session and transaction as class members. During the Struts 2 project initialization, “Full Hibernate Plugin” will injects the corresponding Hibernate session and transaction into the class members using @SessionTarget and@TransactionTarget annotation respectively.

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

In Action class, call the DAO class to perform the database operation.

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 page

JSP pages to add and list the customer.

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 extends the “hibernate-default” instead of the “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.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. Demo

Access it : http://localhost:8080/Struts2Example/listCustomerAction.action

Struts 2 full hibernate plugin example
Struts 2 full hibernate plugin example






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值