dineshonjava

Struts 2 Hibernate 3 Integration Example with Spring 3

In this example we will describe the integration of Struts2 with Hibernate3 as well as using Spring 3 and Tiles2 in this example. We recommend firstly you have a look to previous examples Struts2 with Spring3 Integration Example and  Struts2 with Tiles2 Integration Example.

Hibernate is a high-performance Object/Relational persistence and query service which is licensed under the open source GNU Lesser General Public License (LGPL) and is free to download. If you are not familiar with Hibernate then you can check our Hibernate tutorial.
And if you are not familiar with Spring then you can check our Spring tutorial.

Step 1: Create a Database DOJDB on MySQL Database and also we create User table on this database.

CREATE TABLE User(
   ID   BIGINT NOT NULL AUTO_INCREMENT,
   USERNAME VARCHAR(20) NOT NULL,
   AGE  BIGINT NOT NULL,
   GENDER VARCHAR(20) NOT NULL,
   JOBTYPE VARCHAR(20) NOT NULL
   HOBBIES VARCHAR(20) NOT NULL
   PRIMARY KEY (ID)
);
Step 2: Create a database.properties for database configuration information in the resources folder under src folder in the created project.
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/DOJDB
database.user=root
database.password=root
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
Step 3: Create a Dynamic Web Project with a name Struts2Hibernate3Spring3Tile2Integration and create packages com.dineshonjava.struts2.action, com.dineshonjava.struts2.bean, com.dineshonjava.struts2.dao, com.dineshonjava.struts2.service, com.dineshonjava.struts2.model, com.dineshonjava.struts2.utils under the src folder in the created project.

Step 4: Add below mentioned Struts 2, Hibernate 3 and Spring 3 related libraries and other libraries into the folder WebRoot/WEB-INF/lib.
Struts 2 Hibernate 3 Integration Example with Spring 3

Step 5: Create a Java class UserAction, UserBean, User, UserDao, UserDaoImpl, UserService, UserServiceImpl, CommonUtility under the respective packages.

Step 6: Create Spring configuration files web.xml, applicationContext.xml, tiles-def.xml under the WebRoot/WEB-INF/ and struts.xml under src/resources folders.

Step 7: Create View files under the /WebRoot/ folder. Create a view file mainTemplate.jsp, users.jsp, body.jsp, menu.jsp, haeder.jsp, footer.jsp etc.

Step 8: Project Structure
Struts Hibernate Integration Example with Spring


APPLICATION ARCHITECTURE
We will have a layered architecture for our demo application. The database will be accessed by a Data Access layer popularly called as DAO Layer. This layer will use Hibernate API to interact with database. The DAO layer will be invoked by a service layer. In our application we will have a Service interface called UserService.

Struts 2 Hibernate 3 Integration Example

Step 9: Hibernate Configuration file with Spring Dependencies 

applicationContext.xml
<?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:context="http://www.springframework.org/schema/context"
 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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
 
 <context:component-scan base-package="com.dineshonjava.struts2" />
 
 <!-- Database Configuration Start here-->
 <context:property-placeholder location="classpath:database.properties"/>
 <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
 <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
   <property name="driverClassName" value="${database.driver}"></property>
   <property name="url" value="${database.url}"></property>
   <property name="username" value="${database.user}"></property>
   <property name="password" value="${database.password}"></property>
 </bean>
 <bean class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" id="sessionFactory">
   <property name="dataSource" ref="dataSource"></property>
   <property name="annotatedClasses">
     <list>
       <value>com.dineshonjava.struts2.model.User</value>
     </list>
   </property>
   <property name="hibernateProperties">
    <props>
      <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
      <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
      <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}  </prop>    
         </props>
       </property>
 </bean>
 
  <bean class="org.springframework.orm.hibernate3.HibernateTransactionManager" id="hibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>
  </bean>
 <!-- Database Configuration End Here-->
 
 
 <bean id="user" class="com.dineshonjava.struts2.action.UserAction"/>
    <bean id="userBean" class="com.dineshonjava.struts2.bean.UserBean"/>
</beans>
Let us go through the hibernate configuration only because rest is Spring dependency already know in spring tutorial. First, we declared that we are using MySQL driver. Then we declared the jdbc url for connecting to the database. Then we declared the connection's username, password and pool size. We also indicated that we would like to see the SQL in the log file by turning on "show_sql" to true. Please go through the hibernate tutorial to understand what these properties mean. Finally, we set the mapping class to com.dineshonjava.struts2.model.User which we will create in this chapter.

Step 10: Create Action class and Other classes related to Application.
 UserBean.java
package com.dineshonjava.struts2.bean;

/**
 * @author Dinesh Rajput
 *
 */
public class UserBean {
 private String userName;
 private Long userAge;
 private String userGender;
 private String userJob;
 private String []userHobbies;
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public Long getUserAge() {
  return userAge;
 }
 public void setUserAge(Long userAge) {
  this.userAge = userAge;
 }
 public String getUserGender() {
  return userGender;
 }
 public void setUserGender(String userGender) {
  this.userGender = userGender;
 }
 public String getUserJob() {
  return userJob;
 }
 public void setUserJob(String userJob) {
  this.userJob = userJob;
 }
 public String[] getUserHobbies() {
  return userHobbies;
 }
 public void setUserHobbies(String[] userHobbies) {
  this.userHobbies = userHobbies;
 }
}
User.java
package com.dineshonjava.struts2.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author Dinesh Rajput
 *
 */
@Entity
@Table(name="User")
public class User implements Serializable {

 private static final long serialVersionUID = 1L;
 
 @Id  
 @GeneratedValue(strategy=GenerationType.AUTO)  
 @Column(name = "id")
 private Long userId;
 @Column(name="username")
 private String userName;
 @Column(name="age")
 private Long userAge;
 @Column(name="gender")
 private String userGender;
 @Column(name="jobtype")
 private String userJobType;
 @Column(name="Hobbies")
 private String userHobbies;
 public Long getUserId() {
  return userId;
 }
 public void setUserId(Long userId) {
  this.userId = userId;
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public Long getUserAge() {
  return userAge;
 }
 public void setUserAge(Long userAge) {
  this.userAge = userAge;
 }
 public String getUserGender() {
  return userGender;
 }
 public void setUserGender(String userGender) {
  this.userGender = userGender;
 }
 public String getUserJobType() {
  return userJobType;
 }
 public void setUserJobType(String userJobType) {
  this.userJobType = userJobType;
 }
 public String getUserHobbies() {
  return userHobbies;
 }
 public void setUserHobbies(String userHobbies) {
  this.userHobbies = userHobbies;
 }
}
UserDao.java
package com.dineshonjava.struts2.dao;

import java.util.List;

import com.dineshonjava.struts2.model.User;

/**
 * @author Dinesh Rajput
 *
 */
public interface UserDao {
 void saveUser(User user);
 
 List<User> getUserList(); 
}
UserDaoImpl.java
package com.dineshonjava.struts2.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.dineshonjava.struts2.model.User;

/**
 * @author Dinesh Rajput
 *
 */
@Repository("userDao")  
public class UserDaoImpl implements UserDao {

 @Autowired  
 private SessionFactory sessionFactory;  
 
 @Override
 public void saveUser(User user) {
  sessionFactory.getCurrentSession().saveOrUpdate(user);
 }

 @SuppressWarnings("unchecked")
 @Override
 public List<User> getUserList() {
  return (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class).list();
 }
}
UserService.java
package com.dineshonjava.struts2.service;

import java.util.List;

import com.dineshonjava.struts2.model.User;

/**
 * @author Dinesh Rajput
 *
 */
public interface UserService {
 void saveUser(User user);
 
 List<User> getUserList(); 
}

UserServiceImpl.java
package com.dineshonjava.struts2.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dineshonjava.struts2.dao.UserDao;
import com.dineshonjava.struts2.model.User;

/**
 * @author Dinesh Rajput
 *
 */
@Service("userService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true) 
public class UserServiceImpl implements UserService {

 @Autowired
 private UserDao userDao;
 
 @Override
 @Transactional(propagation = Propagation.REQUIRED, readOnly = false)  
 public void saveUser(User user) {
  userDao.saveUser(user);
 }

 @Override
 public List<User> getUserList() {
  return userDao.getUserList();
 }
}
CommonUtility.java
package com.dineshonjava.struts2.utils;

import java.util.ArrayList;
import java.util.List;

import com.dineshonjava.struts2.bean.UserBean;
import com.dineshonjava.struts2.model.User;

/**
 * @author Dinesh Rajput
 *
 */
public class CommonUtility {
 public static User createModel(UserBean userBean){
  User user = new User();
  user.setUserName(userBean.getUserName());
  user.setUserAge(userBean.getUserAge());
  user.setUserGender(userBean.getUserGender());
  user.setUserJobType(userBean.getUserJob());
  user.setUserHobbies(convertArrayToCsv(userBean.getUserHobbies()));
  return user;
 }
 
 public static List<UserBean> createUserBeanList(List<User> users){
  List<UserBean> beans = new ArrayList<UserBean>();
  UserBean userBean = null;
  for(User user : users){
   userBean = new UserBean();
   userBean.setUserName(user.getUserName());
   userBean.setUserAge(user.getUserAge());
   userBean.setUserGender(user.getUserGender());
   userBean.setUserJob(user.getUserJobType());
   userBean.setUserHobbies(convertCsvToArr(user.getUserHobbies()));
   beans.add(userBean);
  }
  return beans;
  
 }
 public static String convertArrayToCsv(String [] arr){
  String csv = "";
  for(String value : arr){
   csv += value+",";
  }
  return csv;
 }
 public static String[] convertCsvToArr(String csv){
  String [] values = csv.split(",");
  return values;
 }
}
UserAction.java
package com.dineshonjava.struts2.action;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.dineshonjava.struts2.bean.UserBean;
import com.dineshonjava.struts2.model.User;
import com.dineshonjava.struts2.service.UserService;
import com.dineshonjava.struts2.utils.CommonUtility;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @author Dinesh Rajput
 *
 */
public class UserAction extends ActionSupport implements ModelDriven<UserBean>{

 private static final long serialVersionUID = 1L;
 
 @Autowired
 private UserBean userBean;
 @Autowired
 private UserService userService;
 private List<UserBean> users;

 public String execute() {
  users = CommonUtility.createUserBeanList(userService.getUserList());
  return "user";
 }
 
 public String addUser(){
  userService.saveUser(CommonUtility.createModel(userBean));
  users = CommonUtility.createUserBeanList(userService.getUserList());
  return "addUser";
 }
 public String listUser(){
  users = CommonUtility.createUserBeanList(userService.getUserList());
  return "users";
 }
 
 @Override
 public UserBean getModel() {
  return userBean;
 }
 public String alia() { 
  return "alia";
 }
 public String madhuri() { 
  return "madhuri"; 
 }
 public String user() { 
  return "user"; 
 }

 public List<UserBean> getUsers() {
  return users;
 }

 public void setUsers(List<UserBean> users) {
  this.users = users;
 }
 
}
Create view files:
Let us now create the mainTemplate.jsp view file with the following content:
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><tiles:insertAttribute name="title" ignore="true"></tiles:insertAttribute>
</title>
</head>

<body>
  <table border="1">
   <tr>
    <td colspan="2"><tiles:insertAttribute name="header"></tiles:insertAttribute><br/></td>
   </tr>
   <tr>
    <td><tiles:insertAttribute name="menu" /></td>
    <td><tiles:insertAttribute name="body" /></td>
   </tr>
   <tr>
    <td colspan="2"><tiles:insertAttribute name="footer" /></td>
   </tr>
  </table>
</body>
</html>

body.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<style type="text/css">
b{color:navy; background-color: orange;}  
</style>
<title>Struts2-Spring-Tiles integration | dineshonjava.com</title>
</head>
<body>

 <h2>Add User</h2><b>
    <s:form  action="addUsermenu">
    <s:textfield name="userName" key="user.name" />
    <s:textfield name="userAge" key="user.age" value=""/>
    <s:radio name="userGender" key="user.gender" list="{'Male','Female'}" />
    <s:select name="userJob"  key="user.job" list="%{#{'Software':'Software','Hardware':'Hardware','Networking':'Networking','Marketing':'Marketing'}}"/>  
    <s:checkboxlist name="userHobbies" key="user.hobby" list="{'Cricket','Football','Drawing','Cooking','Driving','Movie'}" />  
    <s:submit key="submit" align="center"/>
 </s:form>
 </b>
 <s:if test="%{users.isEmpty()}"> 
 </s:if>
 <s:else>
  <b>List of Users</b>
   <table border="1">
       <tr>
          <td><b>Name</b></td>
          <td><b>Age</b></td>
          <td><b>Gender</b></td>
          <td><b>Job Type</b></td>
          <td><b>Hobbies</b></td>
       </tr>
   <s:iterator value="users"> 
          <tr>
             <td><s:property value="userName"/></td>
             <td><s:property value="userAge"/></td>
             <td><s:property value="userGender"/></td>
              <td><s:property value="userJob"/></td>
              <td><s:property value="userHobbies"/></td>
            </tr>
       </s:iterator>
       </table>
       </s:else>
 </body>
</html>
menu.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
 <a href="<s:url action="usermenu"/>"> <h2>Add User</h2></a><br>
 <a href="<s:url action="aliamenu"/>"><h2>Alia Bhatt</h2></a><br>
    <a href="<s:url action="madhurimenu"/>"><h2>Madhuri Dixit</h2></a><br>

footer.jsp
<center><p><h2>Copyright &copy; 2013 dineshonjava.com</h2></p> </center>

header.jsp
<table>
  <tr>
   <td><img src="http://2.bp.blogspot.com/-rBLnvKuVDO0/UWBnJJ4n1yI/AAAAAAAADCQ/Vh_cVJ34JFw/s1600/new-logo.png" /></td>
    <td><h1><span style="background-color: #FFFFcc">Struts2-Hibernate3-Tiles2-Spring3 integration</span></h1></td>
  </tr>
</table>
users.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <a href="user">Struts2Spring3Hibernate3Tiles Example</a>
</body>
</html>
madhuri.jsp
<img src="http://www.topnews.in/files/Madhuri-Dixit_10.jpg" height="430" width="500" alt="Madhuri Dixit"/>

alia.jsp
<img src="http://cdntopics.onepakistan.com/wp-content/uploads/2012/10/Alia-Bhatt1.jpg" alt="Alia Bhatt"/>

Struts Configuration:
Let us put it all together using struts.xml:
<?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.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
 
 <package name="user" extends="struts-default" namespace="/">
        <result-types>
         <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
       </result-types>
        <action name="user" class="user" method="execute">
            <result name="user" type="tiles">mainTemplate</result>
        </action>
        <action name="*menu" class="user" method="{1}">
            <result name="user" type="tiles">mainTemplate</result>
            <result name="madhuri" type="tiles">madhuri</result>
            <result name="alia" type="tiles">alia</result>
            <result name="addUser" type="tiles">mainTemplate</result>
        </action>
    </package>
 </struts>
myapp.properties
user.name=User Name
user.age=User Age
user.gender=Gender
user.job=Job Type
user.hobby=Hobbies
submit=Add User

Tiles Configuration file-
tiles-def.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE tiles-definitions PUBLIC
   "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
   "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">

<tiles-definitions>

   <definition name="mainTemplate" template="/mainTemplate.jsp">
      <put-attribute name="title"  value="User Registration Form"/>
      <put-attribute name="header" value="/header.jsp"/>
      <put-attribute name="menu"   value="/menu.jsp"/>
      <put-attribute name="body"   value="/body.jsp"/>
      <put-attribute name="footer"   value="/footer.jsp"/>
   </definition>

   <definition name="alia" extends="mainTemplate">
      <put-attribute name="title"  value="Alia Bhatt"/>
      <put-attribute name="body"   value="/alia.jsp"/>      
   </definition>

   <definition name="madhuri" extends="mainTemplate">
      <put-attribute name="title"  value="Madhuri Dixit"/>
      <put-attribute name="body"   value="/madhuri.jsp"/>      
   </definition>
   
   <definition name="success" extends="mainTemplate">
      <put-attribute name="title"  value="User Added Successfully"/>
      <put-attribute name="body"   value="/success.jsp"/>      
   </definition>
  
</tiles-definitions>

create deployment descriptor
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2Hibernate3Spring3Tile2Integration</display-name>
  <welcome-file-list>
        <welcome-file>users.jsp</welcome-file>
    </welcome-file-list>
    <context-param>
    <param-name>
       org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG
    </param-name>
    <param-value>
       /WEB-INF/tiles-def.xml
    </param-value>
   </context-param>
   <listener>
      <listener-class>
         org.springframework.web.context.ContextLoaderListener
      </listener-class>
   </listener>
   <listener>
       <listener-class>
        org.apache.struts2.tiles.StrutsTilesListener
       </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>
</web-app>

Now right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access

URL http://localhost:8080/doj/user

This will give you following screen:

output


Fill data of user form and submit let see following screen we will get.

http://localhost:8080/doj/addUsermenu.action
output


http://localhost:8080/doj/madhurimenu.action
output





Download Source Code + Libs
Struts2Hibernate3Spring3Tile2Integration.zip



<<Previous <<   || Index ||   >>Next >>