Integrate Spring 3, Struts 2 and Hibernate 3

Introduction

This tutorial shows how to integrate Spring 3, Struts 2 and Hibernate 3 in the following example. In this example, Struts 2 will be used as a web framework and Spring 3 will be used as a core service. We will use ORM (Object Relational Mapping) framework Hibernate for our persistent layer to interact with database.

We are going to use MySQL database for our example, you may use any database of your choice.

You may also like to read:

Struts 2, Spring 4, Hibernate 4 and Maven Integration

Prerequisites

Knowledge of Spring, Struts 2 and Hibernate frameworks

Eclipse IDE, Java version at least 1.6, Tomcat at least 7

Spring Framework 3.1.1, Hibernate 3.6.3, Struts 2.3.15.1

Example with Source Code

Creating Project

Create a maven based project in Eclipse or any Java based IDE. Select webapp arctype for creating web application in Eclipse. The name of the project in Eclipse is spring3-strust2-hibernate3.

Updating pom.xml

Once you have created maven project in Eclipse, make sure to update the pom.xml file with the below source:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.roytuts</groupId>
	<artifactId>spring3-strust2-hibernate3</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-asm</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-struts</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.3.15.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-spring-plugin</artifactId>
			<version>2.3.15.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-dojo-plugin</artifactId>
			<version>2.3.15.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>3.6.3.Final</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.23</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.3</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging-api</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-validator</groupId>
			<artifactId>commons-validator</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-digester</groupId>
			<artifactId>commons-digester</artifactId>
			<version>2.0</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-chain</groupId>
			<artifactId>commons-chain</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.0</version>
		</dependency>
		<dependency>
			<groupId>dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>1.6.1</version>
		</dependency>
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.19</version>
		</dependency>
		<dependency>
			<groupId>antlr</groupId>
			<artifactId>antlr</artifactId>
			<version>2.7.6</version>
		</dependency>
		<dependency>
			<groupId>asm</groupId>
			<artifactId>asm</artifactId>
			<version>3.3.1</version>
		</dependency>
		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.4.GA</version>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>spring3-strust2-hibernate3</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.6.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Creating Table in MySQL

We are going to store data into database and also we will fetch data from MySQL database, so we need to create a table in MySQL database. We will create only one table called Cds, which will store information about cds.

CREATE TABLE cds (
	id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
	title varchar(200) COLLATE latin1_general_ci DEFAULT NULL,
	interpret varchar(200) COLLATE latin1_general_ci DEFAULT NULL,
	PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

Inserting some data to the table

We want to build the application and at the same time we would also test the application in order to verify whether the integration of spring 3, struts 2 and hibernate 3 works as expected or not. If you do not insert any data then you will see the page with “No data found”.

Therefore we want to insert some sample data initially by SQL script.

insert into cds(id,title,interpret)
	values
	(1,'Beauty','Ryuichi Sakamoto'),
	(4,'Goodbye Country (Hello Nightclub)','Groove Armada'),
	(5,'Glee','Bran Van 3000');

Creating Hibernate configuration

We will create hibernate configuration file called hibernate.cfg.xml and put it under src/main/resources classpath directory.

The same configuration could be written into hibernate.properties file as well. If you put both hibernate XML and properties files in the classpath then configurations in XML file will override the configurations in hibernate properties file.

The below configuration file configures all the parameters required to establish a database connection and perform database queries through hibernate API.

Please make sure you do not use the optional parameters hibernate.show_sql and hibernate.format_sql in production environment; these parameters are supposed to be used in development environment because you won’t want end users should see your queries in the log.

If may or may not want to specify the batch size; if you do not use then hibernate will use default batch size for query processing.

If you do not want database commit should be performed automatically then you can remove the parameter hibernate.connection.autocommit.

You need to include all the XML mapping files (for example, Cds.hbm.xml) into the configuration file. We will see what is mapping file later.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/cdcol?zeroDateTimeBehavior=convertToNull
		</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.current_session_context_class">thread</property>
		<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory
		</property>
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>
		<property name="hibernate.jdbc.batch_size">50</property>
		<property name="hibernate.connection.autocommit">true</property>
		<mapping
			resource="com/roytuts/struts/spring/domain/Cds.hbm.xml" />
	</session-factory>
</hibernate-configuration>

Creating Domain Object

Creating XML mapping

We will create domain object model called hibernate XML mapping file – Cds.hbm.xml and will put into the same package where we will put the corresponding hibernate Java mapping class.

The below mapping file is required to map your Java object with database table columns otherwise hibernate won’t be able to save your data to database or fetch data from database into your Java object.

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.roytuts.struts.spring.domain.Cds" table="cds"
		catalog="cdcol">
		<id name="id" type="java.lang.Long">
			<column name="id"></column>
			<generator class="identity"></generator>
		</id>
		<property name="title" type="string">
			<column name="title" length="200"></column>
		</property>
		<property name="interpret" type="string">
			<column name="interpret" length="200"></column>
		</property>
	</class>
</hibernate-mapping>

Creating Java Mapping

This domain object class is a simple POJO class, which is responsible for representing the database columns with Java class’s attributes.

This file must have no-argument constructor in order to properly work with hibernate.

package com.roytuts.struts.spring.domain;
import java.io.Serializable;
public class Cds implements Serializable {
	private static final long serialVersionUID = 1L;
	private Long id;
	private String title;
	private String interpret;
	public Cds() {
	}
	public Cds(String title, String interpret) {
		this.title = title;
		this.interpret = interpret;
	}
	public Long getId() {
		return this.id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getTitle() {
		return this.title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getInterpret() {
		return this.interpret;
	}
	public void setInterpret(String interpret) {
		this.interpret = interpret;
	}
}

Spring Service

This service layer code will do the actual business while it communicates with data access layer for perform database activities.

Creating Interface

package com.roytuts.struts.spring.service;
import java.util.List;
import com.roytuts.struts.spring.vo.Cd;
public interface CDService {
	List<Cd> getCDs();
}

Creating Implementation

package com.roytuts.struts.spring.service.impl;
import java.util.ArrayList;
import java.util.List;
import com.roytuts.struts.spring.dao.CDDao;
import com.roytuts.struts.spring.domain.Cds;
import com.roytuts.struts.spring.service.CDService;
import com.roytuts.struts.spring.vo.Cd;
public class CDServiceImpl implements CDService {
	private CDDao cdDao;
	public CDDao getCdDao() {
		return cdDao;
	}
	public void setCdDao(CDDao cdDao) {
		this.cdDao = cdDao;
	}
	@Override
	public List<Cd> getCDs() {
		List<Cds> cds = cdDao.getCDs();
		List<Cd> list = new ArrayList<Cd>();
		for (Cds c : cds) {
			Cd cd = new Cd();
			cd.setId(c.getId());
			cd.setTitle(c.getTitle());
			cd.setInterpret(c.getInterpret());
			list.add(cd);
		}
		return list;
	}
}

Creating VO

It is not a good idea to use the hibernate mapping class or entity class into service layer code. So always create VO or DTO class for corresponding entity class.

package com.roytuts.struts.spring.vo;
public class Cd {
	private Long id;
	private String title;
	private String interpret;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getInterpret() {
		return interpret;
	}
	public void setInterpret(String interpret) {
		this.interpret = interpret;
	}
}

Spring DAO

This is the data access layer responsible for saving, updating, fetching and deleting data from database or any other persistent storage media.

Creating Interface

package com.roytuts.struts.spring.dao;
import java.util.List;
import com.roytuts.struts.spring.domain.Cds;
public interface CDDao {
	List<Cds> getCDs();
}

Creating Implementation

package com.roytuts.struts.spring.dao.impl;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.roytuts.struts.spring.dao.CDDao;
import com.roytuts.struts.spring.domain.Cds;
public class CDDaoImpl extends HibernateDaoSupport implements CDDao {
	@Override
	@SuppressWarnings("unchecked")
	public List<Cds> getCDs() {
		List<Cds> cds = getHibernateTemplate().find("from Cds");
		return cds;
	}
}

Struts Action class

This struts action class is responsible for handling client’s request and response and finally communicates with service layer for further action.

package com.roytuts.struts.spring.action;
import java.util.List;
import org.apache.struts2.dispatcher.DefaultActionSupport;
import com.roytuts.struts.spring.service.CDService;
import com.roytuts.struts.spring.vo.Cd;
public class CDAction extends DefaultActionSupport {
	private static final long serialVersionUID = 1L;
	private List<Cd> cds;
	private CDService cdService;
	public List<Cd> getCds() {
		return cds;
	}
	public void setCds(List<Cd> cds) {
		this.cds = cds;
	}
	public CDService getCdService() {
		return cdService;
	}
	public void setCdService(CDService cdService) {
		this.cdService = cdService;
	}
	public String getListOfCds() {
		if (cds == null) {
			cds = cdService.getCDs();
		}
		return SUCCESS;
	}
}

Struts Configuration

This struts configuration file is by default kept under classpath and it is responsible for required struts configurations, such as namespace, whether it is dev, sit or prod environment, multi-part configuration for file upload, mappings etc. Put this file under src/main/resources folder.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<package name="default" namespace="/" extends="struts-default">
		<action name="retrieveCds" class="retrieveCdAction"
			method="getListOfCds">
			<result name="success">/list.jsp</result>
		</action>
	</package>
</struts>

Spring Configuration

This spring configuration file is responsible for creating necessary beans required in the application. Put this file under src/main/resources folder.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
	<!--Hibernate session factory configuration -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation"
			value="classpath:hibernate.cfg.xml"></property>
	</bean>
	<!-- Hibernate transaction manager -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- Spring and Struts beans -->
	<!-- action -->
	<bean id="retrieveCdAction"
		class="com.roytuts.struts.spring.action.CDAction">
		<property name="cdService" ref="cdService"></property>
	</bean>
	<!-- service -->
	<bean id="cdService"
		class="com.roytuts.struts.spring.service.impl.CDServiceImpl">
		<property name="cdDao" ref="cdDao"></property>
	</bean>
	<!-- dao -->
	<bean id="cdDao"
		class="com.roytuts.struts.spring.dao.impl.CDDaoImpl">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
</beans>

Web Deployment Descriptor

This is the entry point of the web application. Put this file under WEB-INF folder.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<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>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

View Files

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%
	String ctx = request.getContextPath();
	response.sendRedirect(ctx + "/retrieveCds");
%>

list.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<title>Struts2, Spring3 and Hibernate3 Integration Example</title>
<h2>List of Cds</h2>
<s:if test="cds.size() > 0">
	<s:iterator value="cds"></s:iterator>
	<table cellpadding="5px" border="1px">
		<tbody>
			<tr>
				<th>CD Id</th>
				<th>Title</th>
				<th>Interpret</th>
			</tr>
			<tr>
				<td><s:property value="id"></s:property></td>
				<td><s:property value="titel"></s:property></td>
				<td><s:property value="interpret"></s:property></td>
			</tr>
		</tbody>
	</table>
</s:if>
<s:else>
No CD found!
</s:else>

Testing the Application

Deploy the application into Tomcat server and hit the URL http://localhost:8080/spring3-strust2-hibernate3 in the browser. If you don’t have any data in the database then you will see the following page in the browser:

spring 3 struts 2 hibernate 3

download source code

Thank’s for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *