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.

You may also like to read:

Struts 2, Spring 4, Hibernate 4 and Maven Integration

Download the required jars for Spring from https://spring.io, Struts from http://struts.apache.org/download.cgi#struts2316 and Hibernate from http://hibernate.org/orm/downloads/

Create web application using Eclipse or any Java based IDE.

Please make sure you have the following list of jar files in your classpath.

spring, struts and hibernate integration examplespring, struts and hibernate integration examplespring, struts and hibernate integration example

Create Table in MySQL

We are going to store data into database and also we will fetch data from 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=6 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

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

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');

Create Hibernate configurations and Model class

Configuration file : hibernate.cfg.xml

This below XML file is called hibernate configuration file and the same configuration could be written into hibernate.properties file as well. If you put hibernate XML and properties files in the classpath then configurations in XML file will override the 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 into the configuration file. We will see what is mapping file later.

<?xml version="1.0" encoding="UTF-8"?>
<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/jsfspring/domain/Cds.hbm.xml">
</mapping>
</session-factory>
</hibernate-configuration>

Hibernate mapping file : Cds.hbm.xml

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"?>
<hibernate-mapping>
<class name="com.jsfspring.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>

Model Class : Cds.java

This 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.jsfspring.domain;

public class Cds implements java.io.Serializable {
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.

package in.sblog.service;
import in.sblog.domain.Cds;
import java.util.List;
public interface CDService {
public List getCDs();
}
package in.sblog.service;
import in.sblog.dao.CDDao;
import in.sblog.domain.Cds;
import java.util.List;
public class CDServiceImpl implements CDService {
private CDDao cdDao;
public CDDao getCdDao() {
return cdDao;
}
public void setCdDao(CDDao cdDao) {
this.cdDao = cdDao;
}
@Override
public List getCDs() {
List cds = cdDao.getCDs();
return cds;
}
}

Spring DAO layer

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

package in.sblog.dao;
import in.sblog.domain.Cds;
import java.util.List;
public interface CDDao {
public List getCDs();
}
package in.sblog.dao;
import in.sblog.domain.Cds;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class CDDaoImpl extends HibernateDaoSupport implements CDDao {
@Override
public List getCDs() {
List 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 in.sblog.action;
import in.sblog.domain.Cds;
import in.sblog.service.CDService;
import java.util.List;
import org.apache.struts2.dispatcher.DefaultActionSupport;
public class CDAction extends DefaultActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private List cds;
private CDService cdService;
public List getCds() {
return cds;
}
public void setCds(List 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 file – struts.xml

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.

<?xml version="1.0" encoding="UTF-8"?>
<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 file – Application Context

This spring configuration file is responsible for creating necessary beans required in the application.

<?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" 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">
<!--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="in.sblog.action.CDAction">
<property name="cdService" ref="cdService"></property>
</bean>
<!-- service --><bean id="cdService" class="in.sblog.service.CDServiceImpl">
<property name="cdDao" ref="cdDao"></property>
</bean>
<!-- dao --><bean id="cdDao" class="in.sblog.dao.CDDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>

Web deployment descriptor

This is the entry point of the web application.

<?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>/WEB-INF/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 and list.jsp

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

[html]
<%@ 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>

Thank’s for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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