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

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.

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.
            
    		com.google.code
    		struts2-fullhibernatecore-plugin
    		2.2
    	

Here’s all the dependency libraries in this tutorial :

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

 version="1.0"?>

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">


     name="com.mkyong.customer.model.Customer" 
		table="customer" catalog="mkyong">
         name="customerId" type="java.lang.Long">
             name="CUSTOMER_ID" />
             class="identity" />
        
         name="name" type="string">
             name="NAME" length="45" not-null="true" />
        
         name="address" type="string">
             name="ADDRESS" not-null="true" />
        
         name="createdDate" type="timestamp">
             name="CREATED_DATE" length="19" not-null="true" />
        
    

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

 version="1.0" encoding="utf-8"?>

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

  
     name="hibernate.bytecode.use_reflection_optimizer">false
     name="hibernate.connection.password">password
     name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong
     name="hibernate.connection.username">root
     name="hibernate.dialect">org.hibernate.dialect.MySQLDialect
     name="show_sql">true
     name="format_sql">true
     name="use_sql_comments">false
     resource="com/mkyong/customer/hibernate/Customer.hbm.xml" />
  

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>
action="addCustomerAction" >
  name="name" label="Name" value="" />
  name="address" label="Address" value="" cols="50" rows="5" />
  />
</s:form>
 
<h2>All Customers</h2>
 
="customerList.size() > 0">
<table border="1px" cellpadding="8px">
	<tr>
		<th>Customer Id</th>
		<th>Name</th>
		<th>Address</th>
		<th>Created Date</th>
	</tr>
	value="customerList" status="userStatus">
		<tr>
			<td>value="customerId" /></td>
			<td>value="name" /></td>
			<td>value="address" /></td>
			<td>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“.

 version="1.0" encoding="UTF-8" ?>

"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
 

   name="struts.devMode" value="true" />
 
   name="default" namespace="/" extends="hibernate-default">
 
     name="addCustomerAction" 
	class="com.mkyong.customer.action.CustomerAction" method="addCustomer" >
        name="success">pages/customer.jsp
    
 
     name="listCustomerAction" 
	class="com.mkyong.customer.action.CustomerAction" method="listCustomer" >
         name="success">pages/customer.jsp
    
 
	

9. Demo

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







你可能感兴趣的:(SSH)