Struts 2 + Hibernate与“完整的Hibernate插件”集成

在最后一个Struts 2 + Hibernate集成示例中,它使用servlet上下文侦听器来处理Hibernate会话,并且将Struts2与Hibernate框架集成起来非常好。

但是,总有一些东西,以提高🙂在本教程中,我们将介绍如何使用Struts2的的插件名为“Struts2的和Hibernate整合完整的Hibernate插件 “,版本2.2GA,通过创建jyoshiriro

请参阅集成步骤摘要:

  1. 将“ Full Hibernate Plugin ” jar放在项目类路径中。
  2. 使用注解“ @SessionTarget ”注入Hibernate会话; 而“ @TransactionTarget ”注入Hibernate事务。
  3. struts.xml中 ,使程序包扩展“ hibernate-default ”,而不是默认堆栈。

见关系:

Struts 2 <-- (Full Hibernate Plugin) ---> Hibernate <-----> Database

注意
本教程是以前的Struts 2 + Hibernate集成示例(servlet上下文侦听器)的更新版本,因此JSP和Hibernate配置几乎相同,只是集成部分略有不同,请尝试比较两者以发现不同之处。

1.项目结构

请参阅此完整的项目文件夹结构。

Struts 2 Hibernate plugin folder structure

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插件”和依赖项

获取所有Struts2,Hibernate,“ Full Hibernate Plugin ”和MySQL依赖库。 由于“ Full Hibernate Plugin ”不支持Maven,因此您需要从官方网站下载并手动将其包含在Maven本地存储库中。

  1. 下载“ Full Hibernate Plugin ”。
  2. 将下载的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
  3. 将其与跟随的Maven坐标链接。
    <dependency>
    		<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 -->
//...

Hibernate验证程序SLF4j依赖项是“ Full Hibernate Plugin ”所必需的,这没有任何意义,因为大多数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客户的休眠映射文件。

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

5. 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

全部链接〜make软件包扩展了“ 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.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

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

下载源代码

下载它– Struts2-Hibernate-FullHibernatePluginExample.zip (12 KB)

参考文献

  1. Struts 2完整的Hibernate插件文档
  2. Struts 2 + Hibernate集成示例(servlet上下文侦听器)
  3. 将库安装到Maven本地存储库中

翻译自: https://mkyong.com/struts2/struts-2-hibernate-integration-with-full-hibernate-plugin/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值