Struts 2 + Spring + Hibernate integration Tutorial

Download it – Struts2-Spring-Hibernate-Integration-Example.zip

In this tutorial, it shows the integration between “Struts2 + Spring + Hibernate“. Make sure you check the following tutorials before continue.

  1. Struts 2 + Hibernate integration example
  2. Struts 2 + Spring integration example
  3. Struts 1.x + Spring + Hibernate integration example

See the summary of integration steps :

  1. Get all the dependency libraries (a lot).
  2. Register Spring’s ContextLoaderListener to integrate Struts 2 and Spring.
  3. Use Spring’s LocalSessionFactoryBean to integrate Spring and Hibernate.
  4. Done, all connected.

See the relationship :

Struts 2 <-- (ContextLoaderListener) --> Spring <-- (LocalSessionFactoryBean) --> Hibernate
This will be a very long tutorial with little explanation, make sure you check the above 3 articles for details explanation.

Tutorials Start…

It will going to create a customer page, with add customer and list customer function. Front end is usingStruts 2 to display, Spring as the dependency injection engine, andHibernate to doing the database operation. Let start…

1. Project structure

Project folder structure.

Struts2 Spring Hibernate Project Structure
Struts2 Spring Hibernate Project 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.Dependency libraries

This tutorials request many dependency libraries.

Struts 2…

        <!-- Struts 2 -->
        <dependency>
	    <groupId>org.apache.struts</groupId>
	    <artifactId>struts2-core</artifactId>
	    <version>2.1.8</version>
        </dependency>
	<!-- Struts 2 + Spring plugins -->
	<dependency>
            <groupId>org.apache.struts</groupId>
	    <artifactId>struts2-spring-plugin</artifactId>
	    <version>2.1.8</version>
        </dependency>

MySQL…

        <!-- MySQL database driver -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.9</version>
	</dependency>

Spring…

    <!-- Spring framework --> 
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring</artifactId>
		<version>2.5.6</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>2.5.6</version>
	</dependency>

Hibernate…

    <!-- 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…

Only the model and mapping files are required, because Spring will handle the Hibernate configuration.

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>
5. Struts 2…

Implements the Bo and DAO design pattern. All the Bo and DAO will be DI by Spring in the Spring bean configuration file. In the DAO, make it extends Spring’sHibernateDaoSupport to integrate Spring and Hibernate integration.

CustomerBo.java

package com.mkyong.customer.bo;
 
import java.util.List;
import com.mkyong.customer.model.Customer;
 
public interface CustomerBo{
 
	void addCustomer(Customer customer);
	List<Customer> listCustomer();
 
}

CustomerBoImpl.java

package com.mkyong.customer.bo.impl;
 
import java.util.List;
import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.dao.CustomerDAO;
import com.mkyong.customer.model.Customer;
 
public class CustomerBoImpl implements CustomerBo{
 
	CustomerDAO customerDAO;
	//DI via Spring
	public void setCustomerDAO(CustomerDAO customerDAO) {
		this.customerDAO = customerDAO;
	}
 
	//call DAO to save customer
	public void addCustomer(Customer customer){
		customerDAO.addCustomer(customer);
	}
 
	//call DAO to return customers
	public List<Customer> listCustomer(){
		return customerDAO.listCustomer();
	}
}

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.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.mkyong.customer.dao.CustomerDAO;
import com.mkyong.customer.model.Customer;
 
public class CustomerDAOImpl extends HibernateDaoSupport 
    implements CustomerDAO{
 
	//add the customer
	public void addCustomer(Customer customer){
		getHibernateTemplate().save(customer);
	}
 
	//return all the customers in list
	public List<Customer> listCustomer(){
		return getHibernateTemplate().find("from Customer");		
	}
 
}

CustomerAction.java – The Struts2 action is no longer need to extends theActionSupport, Spring will handle it.

package com.mkyong.customer.action;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.model.Customer;
import com.opensymphony.xwork2.ModelDriven;
 
public class CustomerAction implements ModelDriven{
 
	Customer customer = new Customer();
	List<Customer> customerList = new ArrayList<Customer>();
 
	CustomerBo customerBo;
	//DI via Spring
	public void setCustomerBo(CustomerBo customerBo) {
		this.customerBo = customerBo;
	}
 
	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());
		customerBo.addCustomer(customer);
 
		//reload the customer list
		customerList = null;
		customerList = customerBo.listCustomer();
 
		return "success";
 
	}
 
	//list all customers
	public String listCustomer() throws Exception{
 
		customerList = customerBo.listCustomer();
 
		return "success";
 
	}
 
}
6. Spring…

Almost all the configuration is done here, at all, Spring is specialized in integration work :).

CustomerBean.xml – Declare the Spring’s beans : Action, BO and DAO.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
 	<bean id="customerAction" class="com.mkyong.customer.action.CustomerAction">
		<property name="customerBo" ref="customerBo" />	
	</bean>
 
	<bean id="customerBo" class="com.mkyong.customer.bo.impl.CustomerBoImpl" >
		<property name="customerDAO" ref="customerDAO" />
	</bean>
 
   	<bean id="customerDAO" class="com.mkyong.customer.dao.impl.CustomerDAOImpl" >
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
 
</beans>

database.properties – Declare the database details.

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mkyong
jdbc.username=root
jdbc.password=password

DataSource.xml – Create a datasource bean.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
 <bean 
   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="location">
     <value>WEB-INF/classes/config/database/properties/database.properties</value>
   </property>
</bean>
 
  <bean id="dataSource" 
         class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
  </bean>
 
</beans>

HibernateSessionFactory.xml – Create a sessionFactory bean to integrate Spring and Hibernate.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
<!-- Hibernate session factory -->
<bean id="sessionFactory" 
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
 
    <property name="dataSource">
      <ref bean="dataSource"/>
    </property>
 
    <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
       </props>
    </property>
 
    <property name="mappingResources">
		<list>
          <value>com/mkyong/customer/hibernate/Customer.hbm.xml</value>
		</list>
    </property>	
 
</bean>
</beans>

SpringBeans.xml – Create a core Spring’s bean configuration file, act as the central bean management.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<!-- Database Configuration -->
	<import resource="config/spring/DataSource.xml"/>
	<import resource="config/spring/HibernateSessionFactory.xml"/>
 
	<!-- Beans Declaration -->
	<import resource="com/mkyong/customer/spring/CustomerBean.xml"/>
 
</beans>
7. JSP page

JSP page to display the element with Struts 2 tags.

customer.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
 
<body>
<h1>Struts 2 + Spring + 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

Link it all ~

<?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="customerAction" method="addCustomer" >
		    <result name="success">pages/customer.jsp</result>
		</action>
 
		<action name="listCustomerAction"
			class="customerAction" method="listCustomer" >
		    <result name="success">pages/customer.jsp</result>
		</action>
 
	</package>
 
</struts>
9. Struts 2 + Spring

To integrate Struts 2 and Spring, just register the ContextLoaderListener listener class, define a “contextConfigLocation” parameter to ask Spring container to parse the “SpringBeans.xml” instead of the default “applicationContext.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>
 
  <context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>/WEB-INF/classes/SpringBeans.xml</param-value>
  </context-param>
 
  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
 
</web-app>
10. Demo

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

Struts2 Spring Hibernate Example
Struts2 Spring Hibernate Example
Reference
  1. Struts 2 + Hibernate integration example
  2. Struts 2 + Spring integration example
  3. Struts 2 + Hibernate example with Full Hibernate Plugin
  4. Struts 1.x + Spring + Hibernate integration example

内容概要:本文围绕列车-轨道-桥梁交互仿真研究,基于Matlab平台构建数值模型,系统分析列车运行过程中轨道与桥梁结构间的动态相互作用机制。研究涵盖多体动力学建模、耦合系统运动方程求解、边界条件设定及仿真结果可视化等关键环节,重点揭示高速行车条件下基础设施的振动传递规律与力学响应特征。该仿真方法可有效评估结构安全性、舒适性指标及疲劳寿命,为轨道交通工程的设计优化与运维管理提供理论支撑和技术路径。文中配套提供了完整的Matlab代码实现方案及操作说明,便于用户复现、验证和拓展相关研究。; 适合人群:具备Matlab编程基础和结构动力学、车辆动力学等相关专业知识的研究生、科研人员及从事铁路工程、桥梁工程与交通系统安全评估的工程技术人才,尤其适合开展轨道交通耦合振动课题的研究者。; 使用场景及目标:①用于高校与科研机构进行列车-轨道-桥梁耦合系统动力学特性的教学演示与科学研究;②支撑高速铁路桥梁的设计优化、运营安全性评估与减振降噪方案验证;③为复杂交通基础设施的多物理场耦合仿真提供建模思路与代码参考。; 阅读建议:建议读者结合所提供的Matlab代码逐模块深入研读,重点关注系统建模假设、质量-刚度-阻尼矩阵构建方法及数值积分算法的实现细节,同时可通过调整参数进行敏感性分析,进一步掌握仿真模型的适用范围与优化方向。
内容概要:本文系统研究了非线性薛定谔方程的物理信息神经网络(PINN)求解方法,提出一种将物理规律嵌入深度学习模型的科学计算新范式。通过构建全连接神经网络架构,将非线性薛定谔方程及其初始/边界条件作为损失函数的核心组成部分,实现了在无须大量标注数据的前提下对复值偏微分方程的高精度数值求解。该方法充分利用自动微分技术精确计算方程残差,有效融合了数据驱动与模型驱动的优势,在光学孤子传播、量子系统演化等典型场景中展现出优异的逼近能力与泛化性能。文中配套提供了完整的Python实现代码,涵盖网络搭建、损失定义、训练优化与结果可视化全流程。; 适合人群:具备Python编程能力与深度学习基础知识,熟悉偏微分方程理论及科学计算的理工科研究生、科研人员,以及从事光学、量子物理、流体力学等领域建模与仿真的工程技术人员。; 使用场景及目标:① 掌握PINN方法的基本原理与实现技巧;② 学习如何将复杂物理方程转化为可训练的神经网络损失项;③ 应用于非线性光学、玻色-爱因斯坦凝聚、水波动力学等问题的仿真与预测;④ 为相关科研课题提供可复现的算法原型与代码参考。; 阅读建议:建议读者结合所提供的Python代码进行动手实践,重点理解神经网络对微分算子的近似机制、损失函数的多任务加权策略以及训练过程中的超参数调优方法,进而可迁移至其他非线性偏微分方程的求解任务,拓展其在交叉学科中的应用边界。
源码下载地址: https://pan.quark.cn/s/a4b39357ea24 微软推出的【AZ-900微软认证】是一项针对初学者的基础级云服务资格认证,其目的在于帮助学习者掌握云概念、微软Azure服务的运作机制以及云解决方案的核心知识。获得这一认证后,考生将能够清晰地理解云计算领域的基础术语、服务模式(包括IaaS、PaaS、SaaS等)以及这些服务在Azure平台上的实际应用方式。 在【必过考题】部分,我们可以观察到两个重点议题,它们分别聚焦于PaaS(平台即服务)的概念阐释和云成本的计算方式。 在第一个议题中,考生被要求辨别关于PaaS的正确性描述。PaaS平台提供了一个开发环境,但并不允许用户直接访问操作系统(Box 1: No)。比如,Azure Web Apps服务可以用来部署web应用,但用户无法直接管理虚拟机或IIS系统。另一方面,PaaS确实具备自动扩展的功能(Box 2: Yes),这表示可以根据实际需求自动增加负载均衡的虚拟机以支持web应用的运行。PaaS框架还为开发人员提供了构建和调整云端应用的工具,预置的应用组件能够有效缩短新应用的编程周期(Box 3: Yes)。 第二个议题同样关注云计算理念的理解,尤其强调IT支出从资本性支出(CapEx)向运营性支出(OpEx)的转型思想。传统的IT投资通常被视为CapEx,而云计算的按需付费机制使企业能够将这部分开支转化为OpEx,从而在财务规划上获得更大的自由度。 在为AZ-900考试做准备时,考生需要特别关注以下几个核心知识点: 1. **云服务模式**:深入理解IaaS(基础设施即服务)、PaaS和SaaS(软件即服务)之间的差异及其各自的应用情境。 2. **Azure服务*...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值