Struts2 & Hibernate 4 integration step by step tutorial to create Sample application

Before proceeding to this tutorial, you can go through my earlier tutorial how to start new struts2 application. In this tutorial we are going to see how to integrate hibernate with struts 2. Let us develop sample application for Adding / Deleting / Listing Items in Inventory using MySQL database with Hibernate support. Later on we can see how to migrate the same application to use DB2 database without changing any java code and query part. Switching to other SQL database requires few changes in Hibernate configuration file which is the main advantage of using Hibernate. Without using hibernate it is very difficult to switch over to any database especially at later stage.

Jars used in this application :

1. Struts 2.3 Jars
2. Hibernate 4.3.6 Jars
3. JDK 1.8.0

Please look at the below image that shows all the required strust 2.3 and hibernate 4.3.6 jars to create this sample application.

hibernate  required jars

Let us see the steps

Step 1 : Create a dynamic project in Eclipse (File->New -> Dynamic Web Project)

Copy all the jars to your class path (lib folder)

Step 2 : Decide database, table and necessary fields for your sample application (In this eg. Sample Application ->Add / Delete / List Item (Inventory), Table -> Items, Fields Used : item_code, item_name, category, price, quantity , createdOn )

Step 3 : Create Hibernate Configuration file (hibernate-cfg.xml) for configuring database connections (In our example, we are going to work with the MySql database “MyDB”)


<?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="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/MyDB
</property>
<property name="connection.username">root</property>
<property name="connection.password">*******</property>

<property name="connection.pool_size">1</property>

<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>

<!-- Display all generated SQL to stdout -->
<property name="show_sql">true</property>

<property name="hbm2ddl.auto">update</property>

<mapping class="net.javaonline.sample.inventory.dto.ItemMaster" />

</session-factory>

</hibernate-configuration>

Please note that the mapping class. ItemMaster is the persistent class for storing item details.

<mapping class=”net.javaonline.sample.inventory.dto.ItemMaster” />

Step 4 : Create a persistent class (Simple Java bean (POJO) class ) for mapping the table (Items) fields using JPA (Java Persistent Annotations). Mapping can be done through Java 1.5 annotations OR JPA module without using hbm.xml file. The whole Persistent class is defined as an Entity. To define POJO class as Entity use @Entity annotation in the beginning of the class. Mapping can also be done without java annotations i.e. using java bean + hibernate.hbm.xml. In our applications, we have mapped using java annotations (JPA module).


package net.javaonline.sample.inventory.dto;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import java.util.Date;

@Entity
@Table(name="Items")
public class ItemMaster implements Serializable{

private static final long serialVersionUID = -1883317581153939034L;

private Long item_code;
private String item_name;
private String category;
private double price ;
private int qty;
//private Date createdOn;

@Temporal(TemporalType.DATE)
@Column (name="createdOn")
private Date createdOn;
public Date getCreatedOn() {
//return new Date();
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}

@Id
@GeneratedValue
@Column(name="item_code")
public Long getItem_code() {
return item_code;
}
public void setItem_code(Long item_code) {
this.item_code = item_code;
}
@Column(name="item_name")
public String getItem_name() {
return item_name;
}
public void setItem_name(String item_name) {
this.item_name = item_name;
}
@Column(name="category")
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
@Column(name="price")
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Column(name="qty")
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}

}

} 

Hibernate even can directly access the fields without getter and setter methods. But it is always recommended to create getter  and setter methods.

Step 5: Create HibernateUtil class to create session factory for database access


package net.javaonline.register.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {

private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}

}

Now Hibernate part is over. The Struts 2 action part starts here

Step 6: Create an Struts 2 Action class for Add / Delete items in database.

package net.javaonline.sample.inventory.controller;
import java.util.List;
import net.javaonline.sample.inventory.controller.ItemMasterDAO;
import net.javaonline.sample.inventory.dto.ItemMaster;
import com.opensymphony.xwork2.ActionSupport;

public class ItemMasterAction extends ActionSupport {

private static final long serialVersionUID = -3761530667134304608L;
private ItemMaster item;
private List<ItemMaster> itemList;
private Long id;
private ItemMasterDAO itemMasterDao;

public ItemMaster getItem() {
return item;
}

public void setItem(ItemMaster item) {
this.item = item;
}
public ItemMasterAction() {
itemMasterDao = new ItemMasterDAO();
}

public String execute() {
this.itemList = itemMasterDao.list();
return SUCCESS;
}

public String add() {
System.out.println(getItem());
try {
ItemMaster item=getItem();
item.setCreatedOn(new java.util.Date()); // for current date to store on createdOn field.
itemMasterDao.add(item);
} catch (Exception e) {
e.printStackTrace();
}
this.itemList = itemMasterDao.list();
return SUCCESS;
}

public String list() {
this.itemList = itemMasterDao.list();
return SUCCESS;
}

public String delete() {
itemMasterDao.delete(getId());
return SUCCESS;
}

public List<ItemMaster> getItemList() {
return itemList;
}
public void setItemList(List<ItemMaster> itemList) {
this.itemList = itemList;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}
} 

Step 7: Create DAO class (ItemMasterDAO) that has been used in the above action class that actually add , delete records using Hibernate session


package net.javaonline.sample.inventory.controller;

import java.util.List;
import net.javaonline.sample.inventory.dto.ItemMaster;
import net.javaonline.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;

public class ItemMasterDAO extends HibernateUtil {

//For adding items in the Items table.
public ItemMaster add(ItemMaster item) {
Session session = HibernateUtil.createSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(item);
session.getTransaction().commit();
return item;
}

//For deleting item from Items table.

public ItemMaster delete(Long id) {
Session session = HibernateUtil.createSessionFactory().getCurrentSession();
session.beginTransaction();
ItemMaster item = (ItemMaster) session.load(ItemMaster.class, id);
if(null != item) {
session.delete(item);
}
session.getTransaction().commit();
return item;
}
// For generating , executing hibernate select query and returns items as a list.

public List<ItemMaster> list() {

Session session = HibernateUtil.createSessionFactory().getCurrentSession();
session.beginTransaction();
List<ItemMaster> items = null;
try {
items = (List<ItemMaster>)session.createQuery("from ItemMaster").list();

} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return items;
}
} 

Step 8: Create JSP file (itemsAddDelete.jsp) for adding , deleting  and listing items.


<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Item Master Entry - Struts2 Hibernate Example</title>
</head>
<body>

<h1>Add / Delete / List Item</h1>
<s:actionerror/>

<s:form action="add" method="post">
<s:textfield name="item.item_name" label="Item Name"/>
<s:textfield name="item.category" label="Category"/>
<s:textfield name="item.price" label="Price"/>
<s:textfield name="item.qty" label="Quantity"/>

<s:submit value="Add Item" align="center"/>
</s:form>

<s:form action="list" method="post">
<s:submit value="List items" align="center"/>
</s:form>

<h2>Items in Master</h2>
<table border="1">
<tr>
<th>Item Code</th>
<th>Item Name</th>
<th>Category</th>
<th>Price</th>
<th>Quantity</th>
<th>Action</th>
</tr>
<s:iterator value="itemList" var="items">
<tr>
<td><s:property value="item_code"/></td>
<td><s:property value="item_name"/></td>
<td><s:property value="category"/></td>
<td><s:property value="price"/></td>
<td><s:property value="qty"/></td>
<td><a href="delete?id=<s:property value="item_code"/>">delete</a></td>
</tr>
</s:iterator>
</table>
</body>
</html> 

Step 9 : create Struts.xml for mapping the action.


<?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="false" />

<package name="default" extends="struts-default" namespace="/">

<action name="add"
class="net.javaonline.sample.inventory.controller.ItemMasterAction" method="add">
<result name="success" type="chain">index</result>
<result name="input" type="chain">index</result>
</action>

<action name="delete"
class="net.javaonline.sample.inventory.controller.ItemMasterAction" method="edit">
<result name="success" type="chain">index</result>
</action>

<action name="delete"
class="net.javaonline.sample.inventory.controller.ItemMasterAction" method="delete">
<result name="success" type="chain">index</result>
</action>

<action name="list"
class="net.javaonline.sample.inventory.controller.ItemMasterAction" method="list">
<result name="success" type="chain">index</result>
</action>

<action name="index" class="net.javaonline.sample.inventory.controller.ItemMasterAction">
<result name="input">/index.jsp</result>
<result name="success">index.jsp</result>
</action>
</package>
</struts> 

Step 10 : Create web.xml as given below


<?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" 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>Struts2Sample</display-name>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<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>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>

</web-app>

Running the above application using http://localhost:8080/Struts2Hibernate/, you will get the below screen.

hibernate struts2 sample apllication
Step 11. Now you can easily migrate your application to run with any Database by changing few lines of code in hibernate.cfg.xml. For eg. if you want to run your application with DB2 database, just replace the hibernate.cfg.xml, with the below one.

<?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="connection.driver_class">
com.ibm.db2.jcc.DB2Driver
</property>
<property name="connection.url">
jdbc:db2://localhost:50000/MyDB
</property>
<property name="connection.username">vkj</property>
<property name="connection.password">******</property>
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.DB2Dialect
</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>

<!-- diaplay all genetated SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

<mapping class="net.javaonline.sample.inventory.dto.ItemMaster" />

</session-factory>

</hibernate-configuration> 

Note : Don’t forget to add db2drivers and java 1.7

You can download the sample application with jars from here

Download War

You may also like

Leave a Reply