Nearby lessons

6 of 19

Hibernate - Integration with Struts

📌 What You Will Learn
  • Understand Hibernate - Integration with Struts
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Hibernate - Integration with Struts step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Integration with Struts

  • <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-

instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.c om/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd" id="WebApp_ID" version="2.5">

  • <display-name>loginapp</display-name>
  • <welcome-file-list>
  • <welcome-file>loginform.html</welcome-file>
  • </welcome-file-list>
  • <servlet>
  • <servlet-name>actionServlet</servlet-name>
  • <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
  • <load-on-startup>1</load-on-startup>
  • </servlet>
  • <servlet-mapping>
  • <servlet-name>actionServlet</servlet-name>
  • <url-pattern>*.do</url-pattern>
  • </servlet-mapping>
  • </web-app>

Integration Of Hibernate with Struts

  • Manual Approach:
  • By Customizing ActionServlet
  • By Using PlugIn Approach

Hibernate

  • Student.java
  • Student.hbm.xml
  • hibernate.cfg.xml
  • HibernateUtil.java
  • StudentService.java

Struts — registrationform.html

  • StudentRegistrationAction.java
  • StudentRegistrationActionForm.java
  • student_registration_form.html
  • success.html
  • failure.html
  • existed.html
  • struts-config.xml
  • web.xml

Example:

Example04
JCode Cell
1 
2<!DOCTYPE html>
3<html>
4<head>
5<meta charset="ISO-8859-1">
6<title>Insert title here</title>
7</head>
8<body>
9<h2>Durga Software Solutions</h2>
10<h3>Student Registration Form</h3>
11<form method="POST" action="reg.do">
12<table>
13<tr>
14<td>Student Id</td>
15<td><input type="text" name="sid"/></td>
16</tr>
17<tr>
18<td>Student Name</td>
19<td><input type="text" name="sname"/></td>
20</tr>
21<tr>
22<td>Student Address</td>
23<td><input type="text" name="saddr"/></td>
24</tr>
25<tr>
26<td><input type="submit" value="Registration"/></td>
27</tr>
28</table>
29</form>
30</body>
31</html>
32

Struts — success.html

Example05
JCode Cell
1 
2<!DOCTYPE html>
3<html>
4<head>
5<meta charset="ISO-8859-1">
6<title>Insert title here</title>
7</head>
8<body>
9<h2>Durga Software Solutions</h2>
10<h3>Student Registration Status</h3>
11<font color="red" size="6">
12<b>
13Student Registration Success
14</b>
15</font>
16<h5>
17<a href="./registrationform.html">|Student Registration Form|</a>
18</h5>
19</body>
20</html>
21

Struts — failure.html

Example06
JCode Cell
1 
2<!DOCTYPE html>
3<html>
4<head>
5<meta charset="ISO-8859-1">
6<title>Insert title here</title>
7</head>
8<body>
9<h2>Durga Software Solutions</h2>
10<h3>Student Registration Status</h3>
11<font color="red" size="6">
12<b>
13Student Registration Failure
14</b>
15</font>
16<h5>
17<a href="./registrationform.html">|Student Registration Form|</a>
18</h5>
19</body>
20</html>
21

Struts — existed.html

Example07
JCode Cell
1 
2<!DOCTYPE html>
3<html>
4<head>
5<meta charset="ISO-8859-1">
6<title>Insert title here</title>
7</head>
8<body>
9<h2>Durga Software Solutions</h2>
10<h3>Student Registration Status</h3>
11<font color="red" size="6">
12<b>
13Student Existed Already
14</b>
15</font>
16<h5>
17<a href="./registrationform.html">|Student Registration Form|</a>
18</h5>
19</body>
20</html>
21

Struts — StudentActionForm.java

Example08
JCode Cell
1 
2package com.durgasoft.beans;
3 
4import org.apache.struts.action.ActionForm;
5 
6public class StudentActionForm extends ActionForm {
7private String sid;
8private String sname;
9private String saddr;
10public String getSid() {
11return sid;
12}
13public void setSid(String sid) {
14this.sid = sid;
15}
16public String getSname() {
17return sname;
18}
19public void setSname(String sname) {
20this.sname = sname;
21}
22public String getSaddr() {
23return saddr;
24}
25public void setSaddr(String saddr) {
26this.saddr = saddr;
27}
28 
29 
30}
31

Struts — StudentAction.java

Example09
JCode Cell
1 
2package com.durgasoft.action;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6 
7import org.apache.struts.action.Action;
8import org.apache.struts.action.ActionForm;
9import org.apache.struts.action.ActionForward;
10import org.apache.struts.action.ActionMapping;
11 
12import com.durgasoft.beans.StudentActionForm;
13import com.durgasoft.service.StudentService;
14 
15public class StudentAction extends Action {
16@Override
17public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
18HttpServletResponse response) throws Exception {
19String status = "";
20StudentActionForm saf = (StudentActionForm)form;
21String sid = saf.getSid();
22String sname = saf.getSname();
23String saddr = saf.getSaddr();
24StudentService stdService = new StudentService();
25status = stdService.registration(sid, sname, saddr);
26return mapping.findForward(status);
27}
28}
29

Struts — StudentService.java

Example10
JCode Cell
1 
2package com.durgasoft.service;
3 
4import org.hibernate.Session;
5import org.hibernate.SessionFactory;
6import org.hibernate.Transaction;
7 
8import com.durgasoft.hbn.pojo.Student;
9import com.durgasoft.hbn.util.HibernateUtil;
10 
11public class StudentService {
12String status = "";
13public String registration(String sid, String sname, String saddr) {
14try {
15 SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
16 Session session = sessionFactory.openSession();
17 Student std = (Student) session.get(Student.class, sid);
18 if(std == null) {
19 std = new Student();
20 std.setSid(sid);
21 std.setSname(sname);
22 std.setSaddr(saddr);
23 Transaction tx = session.beginTransaction();
24 session.save(std);
25 tx.commit();
26 status = "success";
27 }else {
28 status = "existed";
29 }
30} catch (Exception e) {
31 status = "failure";
32 e.printStackTrace();
33}
34return status;
35}
36}
37

Struts — Student.java

Example11
JCode Cell
1 
2package com.durgasoft.hbn.pojo;
3 
4public class Student {
5private String sid;
6private String sname;
7private String saddr;
8 
9public String getSid() {
10 return sid;
11}
12public void setSid(String sid) {
13this.sid = sid;
14}
15public String getSname() {
16return sname;
17}
18public void setSname(String sname) {
19this.sname = sname;
20}
21public String getSaddr() {
22return saddr;
23}
24public void setSaddr(String saddr) {
25this.saddr = saddr;
26}
27 
28 
29}
30

Struts — HibernateUtil.java

Example12
JCode Cell
1 
2package com.durgasoft.hbn.util;
3 
4import org.hibernate.SessionFactory;
5import org.hibernate.cfg.Configuration;
6 
7public class HibernateUtil {
8static SessionFactory sessionFactory;
9static {
10 try {
11 Configuration cfg = new Configuration();
12 cfg.configure("/com/durgasoft/hbn/cfgs/hibernate.cfg.xml");
13 sessionFactory = cfg.buildSessionFactory();
14} catch (Exception e) {
15 e.printStackTrace();
16}
17}
18public static SessionFactory getSessionFactory() {
19return sessionFactory;
20}
21}
22

Struts — Student.hbm.xml

Example13
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-mapping PUBLIC
4"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
6<hibernate-mapping>
7<class name="com.durgasoft.hbn.pojo.Student" table="student">
8 <id name="sid" column="SID"/>
9 <property name="sname" column="SNAME"/>
10 <property name="saddr" column="SADDR"/>
11</class>
12</hibernate-mapping>
13

Struts — hibernate.cfg.xml

Example14
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8 <property name="connection.driver_Class">com.mysql.jdbc.Driver</property>
9 <property name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
10 <property name="connection.username">root</property>
11<property name="connection.password">root</property>
12<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
13<mapping resource="com/durgasoft/hbn/mappings/Student.hbm.xml"/>
14</session-factory>
15</hibernate-configuration>
16

Struts — struts-config.xml

Example15
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE struts-config PUBLIC
4 "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
5 "http://struts.apache.org/dtds/struts-config_1_3.dtd">
6<struts-config>
7<form-beans>
8 <form-bean name="studentActionForm" type="com.durgasoft.beans.StudentActionForm"/>
9</form-beans>
10<action-mappings>
11<action path="/reg" name="studentActionForm" type="com.durgasoft.action.StudentAction">
12 <forward name="success" path="/success.html"/>
13 <forward name="failure" path="/failure.html"/>
14 <forward name="existed" path="/existed.html"/>
15</action>
16 
17</action-mappings>
18</struts-config>
19

Struts — web.xml

Example16
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<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_2_5.xsd" id="WebApp_ID" version="2.5">
4<display-name>struts_hibernate_app1</display-name>
5<welcome-file-list>
6<welcome-file>registrationform.html</welcome-file>
7</welcome-file-list>
8<servlet>
9<servlet-name>actionServlet</servlet-name>
10<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
11<load-on-startup>1</load-on-startup>
12</servlet>
13<servlet-mapping>
14<servlet-name>actionServlet</servlet-name>
15<url-pattern>*.do</url-pattern>
16</servlet-mapping>
17</web-app>
18

Struts

In the above application, Struts Framework will be loaded at the time of Server Startup, because, ActionServlet initialization is performed at the time of Server Startup due to <load-on-startup> configuration in ActionServlet configuration in web.xml file, but, Hibernate software is loaded after the Server startup and after getting first request from client, it may take lot of time to load Hibernate Software, it will increase response time and it will reduce application performance.

In the above context, to improve application performance we have to load Hibernate Software along with Struts framework loading, that is, at the time of Server startup and as part of ActionServlet initialization.

To achieve the above requirement we have to Customize ActionServlet initialization process.

Hibernate integration with Struts by Customizing ActionServlet

1) Prepare Our own Controller class by extending ActionServlet and override "init()"

method

Example19
JCode Cell
1 
2package com.durgasoft.controller;
3import javax.servlet.ServletConfig;
4import javax.servlet.ServletException;
5import org.apache.struts.action.ActionServlet;
6import com.durgasoft.hbn.util.HibernateUtil;
7public class MyController extends ActionServlet {
8public void init(ServletConfig config) throws ServletException {
9super.init(config);
10HibernateUtil.getSessionFactory();
11System.out.println("****MyController-init()**********");
12System.out.println("Struts Framework is Loaded");
13System.out.println("Hibernate is Loaded");
14System.out.println("*********MyController-init()********");
15}
16}
17

Configure User Defined Controller class in web.xml file

  • <web-app>
  • <welcome-file-list>
  • <welcome-file>registrationform.html</welcome-file>
  • </welcome-file-list>
  • <servlet>
  • <servlet-name>myController</servlet-name>
  • <servlet-class>com.durgasoft.controller.MyController</servlet-class>
  • <load-on-startup>1</load-on-startup>
  • </servlet>
  • <servlet-mapping>
  • <servlet-name>myController</servlet-name>
  • <url-pattern>*.do</url-pattern>
  • </servlet-mapping>
  • </web-app>

In Struts based web applications, it is not suggestible to customize predefined controller ActionServlet , because, ActionServlet is having no of responsibilities as part of its initialization, if we have not overridden init() method properly then the total ActionServlet may not be executed, it may not load Struts Framework.

Integration of Hibernate with Struts by using plugin Approach

a) Prepare Hibernate PlugIn class. b) Configure hibernate PlugIn class in struts configuration file.

a) Prepare Hibernate PlugIn class

To prepare Hibernate PlugIn class, declare an user defined class and implement org.apache.struts.action.PlugIn interface and provide implementat6ion for the following methods.

  • public void init(ActionServlet as, ModuleConfig config) throws ServletException
  • public void destroy()
Example22
JCode Cell
1 
2package com.durgasoft.plugin;
3import javax.servlet.ServletException;
4import org.apache.struts.action.ActionServlet;
5import org.apache.struts.action.PlugIn;
6import org.apache.struts.config.ModuleConfig;
7import com.durgasoft.hbn.util.HibernateUtil;
8public class HibernatePlugIn implements PlugIn {
9public void init(ActionServlet arg0, ModuleConfig arg1) throws ServletException {
10System.out.println("****HibernatePlugIn-init()*********");
11HibernateUtil.getSessionFactory();
12System.out.println("Hibernate is Loaded along with Struts Loading");
13System.out.println("*****HibernatePlugIn-init()*********");
14}
15public void destroy() {
16}
17}
18

b) Configure Hibernate Plugin class in Struts configuration File

  • <struts-config>
  • <plug-in className="com.durgasoft.plugin.HibernatePlugIn"/>
  • </struts-config>

Internal Flow

When we start Server, Container will perform the following actions.

  • Container will deploye all web applications which are available in webapps folder or in deployments folder.
  • Container will recognize web.xml file and perform web.xml file loading and parsing.
  • Container will recognize <load-on-startup> configuration in ActionServlet configuration in

web.xml file then performs ActionServlet loading, instantiation and initialization.

  • As part of ActionServlet initialization, ActionServlet will recognize struts configuration file

then performs struts configuration file loading and parsing.

  • ActionServlet will recognize <plug-in> tag in struts configuration file and identify

HibernatePlugIn class .

  • ActionServlet will perform HibernatePlugIn class loading , instantiation and initialization.
  • As part of HibernatePlugIn class initialization,ActionServlet will load Hibernate software and

prepare Configuration and SessionFactory objects with HibernateUtil class at the time of Server startup. Is it possible to interact with more than one Database from a single Hibernate Application?

Ans — Employee.java

Yes, in single hibernate application we are able to interact with more than one Database, but, we must use the following conventions.

1) We must provide separate configuration file for each and every Database. 2) Use either single mapping file if we have same table name and same columns in both the

databases tables and use different mapping file for each and every database if we have difference in table names and column names. 3) In Client application.

  • Prepare Seperate Configuration object for each and every DB.
  • Prepare seperate SessionFactory object for each and every DB.
  • Prepare seperate Session object for each and every DB.
  • Prepare Seperate Transaction object for each and every DB as per the requirement.
  • Perform persistance operations on DB respective Session objects.

Example:

Example25
JCode Cell
1 
2package com.durgasoft.hbn.pojo;
3 
4public class Employee {
5private int eno;
6private String ename;
7private float esal;
8private String eaddr;
9public int getEno() {
10 return eno;
11}
12public void setEno(int eno) {
13this.eno = eno;
14}
15public String getEname() {
16return ename;
17}
18public void setEname(String ename) {
19this.ename = ename;
20}
21public float getEsal() {
22return esal;
23}
24public void setEsal(float esal) {
25this.esal = esal;
26}
27public String getEaddr() {
28return eaddr;
29}
30public void setEaddr(String eaddr) {
31this.eaddr = eaddr;
32}
33}
34

Ans — Employee.hbm.xml

Example26
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-mapping PUBLIC
4"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
6<hibernate-mapping>
7<class name="com.durgasoft.hbn.pojo.Employee" table="emp1">
8 <id name="eno" column="ENO"/>
9 <property name="ename" column="ENAME"/>
10 <property name="esal" column="ESAL"/>
11<property name="eaddr" column="EADDR"/>
12</class>
13</hibernate-mapping>
14

Ans — hibernate_oracle.cfg.xml

Example27
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8 <property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
9 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
10 <property name="connection.user">system</property>
11<property name="connection.password">durga</property>
12<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
13<property name="show_sql">true</property>
14<mapping resource="com/durgasoft/hbn/mappings/Employee.hbm.xml"/>
15</session-factory>
16</hibernate-configuration>
17

Ans — hibernate_mysql.cfg.xml

Example28
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8 <property name="connection.driver_Class">com.mysql.jdbc.Driver</property>
9 <property name="connection.url">jdbc:mysql://localhost:3306/durgadb</property>
10 <property name="connection.user">root</property>
11<property name="connection.password">root</property>
12<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
13<property name="show_sql">true</property>
14<mapping resource="com/durgasoft/hbn/mappings/Employee.hbm.xml"/>
15</session-factory>
16</hibernate-configuration>
17

Ans — ClientApp.java

Example29
JCode Cell
1 
2package com.durgasoft.hbn.client;
3 
4import org.hibernate.Session;
5import org.hibernate.SessionFactory;
6import org.hibernate.Transaction;
7import org.hibernate.cfg.Configuration;
8 
9import com.durgasoft.hbn.pojo.Employee;
10 
11public class ClientApp {
12 
13public static void main(String[] args) {
14SessionFactory oracle_SessionFactory = null;
15SessionFactory mysql_SessionFactory = null;
16Session oracle_Session = null;
17Session mysql_Session = null;
18try {
19 Configuration oracle_Cfg = new Configuration();
20 Configuration mysql_Cfg = new Configuration();
21 
22 oracle_Cfg.configure("hibernate_oracle.cfg.xml");
23 mysql_Cfg.configure("hibernate_mysql.cfg.xml");
24 
25 oracle_SessionFactory = oracle_Cfg.buildSessionFactory();
26 mysql_SessionFactory = mysql_Cfg.buildSessionFactory();
27 
28 oracle_Session = oracle_SessionFactory.openSession();
29 mysql_Session = mysql_SessionFactory.openSession();
30 
31 Employee emp = (Employee) oracle_Session.get(Employee.class, 111);
32 System.out.println("Employee retrived from Oracle DB");
33 
34 Transaction mysql_Tx = mysql_Session.beginTransaction();
35 mysql_Session.save(emp);
36 mysql_Tx.commit();
37 System.out.println("Employee Inserted in MySQL DB");
38 
39} catch (Exception e) {
40 e.printStackTrace();
41}finally {
42 oracle_Session.close();
43 mysql_Session.close();
44 
45 oracle_SessionFactory.close();
46 mysql_SessionFactory.close();
47}
48 
49}
50}
51

Ans

Is it possible to run hibernate applicatins with out using mapping file?

ANS

Yes, it is possible to run hibernate applications with out using mapping file, but, we have to use Annotations. To provide mapping details in Hibernate applications we have to use the following annotations provided by JPA in the form of "javax.persistence" package.

@Entity

It is a class level annotation, it can be used to declare a class as an Entity class.

  • @Table(name="--")

This annotation is a class level annotation, it can be used to configure table name for the entity class. Where "name" member is able to provide the respective table name.

@Id — hibernate.cfg.xml

This annotation is Field/Method[getXXX()] level annotation, it can be used to declare a property as ID property.

  • @Column(name="--")

This annotation is Field/Method[getXXX()] level annotation, it can be used to provide a database table column name inorder to provide mapping .

1) In Hibernate Applications, to use annotations we have to use the following steps. 2) Remove mapping file and provide annotations ion POJO class. 3) In Configuration File , provide <mapping> tag with "class" attribute inplace of "resource"

attribute."class" attribute will take fully qualified name of the respective POJO class. 4) In Client Application, Create Either AnnotationConfiguration object or Configuration object to

process Annotations. Note: AnnotationConfiguration is deprecated class, so it is better to use Configuration class object to process annotations.

Ex: Employee.java

  • @Entity
  • @Table(name="emp1")
  • public class Employee{
  • @Id
  • @Column(name="ENO")
  • private int eno;
  • @Column(name="ENAME")
  • private String ename;
  • @Column(name="ESAL")
  • private float esal;
  • @Column(name="EADDR")
  • private String eaddr;
  • setXXX() and getXXX()
Example33
JCode Cell
1 
2<hibernate-configuration>
3---
4<mapping class="com.durgasoft.hbn.pojo.Employee"/>
5----
6</hibernate-Configuration>
7

ClientApp.java — Employee.java

Same as previous applications.

Example:

Example34
JCode Cell
1 
2package com.durgasoft.hbn.pojo;
3 
4import javax.persistence.Column;
5import javax.persistence.Entity;
6import javax.persistence.Id;
7import javax.persistence.Table;
8 
9@Entity
10@Table(name="emp1")
11public class Employee {
12@Id
13@Column(name="ENO")
14private int eno;
15@Column(name="ENAME")
16private String ename;
17@Column(name="ESAL")
18private float esal;
19@Column(name="EADDR")
20private String eaddr;
21 
22/*
23@Id
24@Column(name="ENO")
25*/
26public int getEno() {
27return eno;
28}
29public void setEno(int eno) {
30this.eno = eno;
31}
32// @Column(name="ENAME")
33public String getEname() {
34return ename;
35}
36public void setEname(String ename) {
37this.ename = ename;
38}
39//@Column(name="ESAL")
40public float getEsal() {
41return esal;
42}
43public void setEsal(float esal) {
44this.esal = esal;
45}
46//@Column(name="EADDR")
47public String getEaddr() {
48return eaddr;
49}
50public void setEaddr(String eaddr) {
51this.eaddr = eaddr;
52}
53 
54 
55}
56

ClientApp.java — hibernate.cfg.xml

Example35
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7
📝 Key Takeaways
  • Key ideas of Hibernate - Integration with Struts explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end