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

Leave a Reply

male potency pills best impotence pill top 10 penis enlargement penis pills with permanent results male enhancement kijiji buying ed pills from india companies x again platinum male enhancement 1350 african back ant male enhancement dominator male enhancement pills alphamaxx male enhancement reviews walgreens best male enhancement male package enhancer uk fast natural penis enlargement penis enlargement excercises penis enlargement herb from africa pure nitrate male enhancement male enhancement drugs over the counter sex pills with mild hypertension erectile dysfunction drugs taken daily best penis enlargement suppliment pe enlargement andy blog male enhancement saw palmetto pills walmart sex drive medication male enhancementredd male enhancement pills for length and girth male extra male enhancement pill diy male enhancement pills is penis enlargement a safe procedure free red male enhancement penis enlargement surgery in ri best penis enlargement pills at walmart permanant penis enlargment pills male enhancement pills heb meijer supplements best garlic supplement store bought sex pills easy penis enlargement tips dexters mom sex pills 4 male enhancement products at walgreens pandora sexual enhancement reviews rhino free trial sex pills duck dynasty male enhancement pills do the penis enlarge pills work jaguaar pills for male enhancement bangladesh hardwood male enhancement cream pills that do nothing but enlarge your penis herbal enhancement

cbd plus pet cbd oil cbd oil for adhd can cbd oil harm the liver best cbd oil for vaping cbd france ananda professional cbd oil cbd oil gifts cbd for asthma full spectrum cbd vs isolate where to buy cbd oil in oklahoma is cbd the same as hemp cbd oil sales near me cbd oil allergy symptoms cbd oil how much is cbd oil legal in nevada is cbd oil good for diabetes cbd blunt wraps cbd promotion code 2020 cbd oil online best brand ecocaps cbd how to extract cbd oil from weed cbd melanoma cbd coffee near me is cbd oil legal in rhode island cbd pain patch cbd laws tn does cbd oil show up on a blood test cbd oil port orange fl how to choose the best cbd oil can i send cbd in the mail cbd oil with adderall cbd comes from cbd oil and sibo free bus sydney cbd how often can you use cbd oil purchase cbd online cbd advertisement 3 cbd sydney how to take cbd oil for anxiety do you put cbd oil under your tongue 6 cbd 6 thc cbd oil south korea cbd security clearance hemp cbd oil drops under tongue cbd oil in checked baggage how much cbd oil one dose karaoke bar melbourne cbd

does the va prescribe weight loss pills weight loss pills without prescriptions what is the quick weight loss diet plan do b12 pills work to lose weight 1600 calorie diet weight loss keto advanced weight loss pills ingredient weight loss pills that work fast without exercise what diet works better for weight loss keto diet recipes cheesie radishes weight loss diet after c section diet plan for thyroid patients to lose weight which weight loss pills are good for diabetes diet foods to lose weight phase one south beach diet weight loss best weight loss pill to lose weight fast do high protein diets work for weight loss weight loss supplements for pcos plant based diet weight loss before and after weight loss on a ketogenic diet keto diet deseret recipes buckwheat weight loss diet lamu weight loss pills diet for weight loss in stomach gm diet weight loss results dream diet weight loss center smoothie diets recipes for weight loss how dangerous are weight loss pills strongest thyroid pills for weight loss rely on weight loss pills weight loss from bean diet sapphire weight loss pills weight loss fiber supplements guaranteed weight loss pills 2020 how to do a smoothie diet for weight loss what is good weight loss pills high carb diet weight loss diet plan 4 weight loss weight loss with apple cider vinegar pills doctor now weight loss diet keto advanced diet pills reviews body building weight loss diet meal plan yanhee hospital weight loss pills what is the best healthy weight loss diet lose weight with tuna and apple diet quick weight loss diet blog lose weight fast no pills no exercise supplements for womens health weight loss best weight loss pills for women reviews