Update data form the database table using Hibernate and jsp page by R4R Team

In the session of the Hibernate and struts2 integration tutorial we will learn how to Update data from the table using User Interfaces. Struts support the all operation which we want to perform. It can understand using the small example on the struts integration with Hibernate. For making the application we need to remember the all concept of hibernate and struts also then we can integrate together the all fame work. For making on this application we need to go through the some basic step which is discussed below:

For making these type of application we need to use anyIDE like as netbeans or it can be eclipse. Database will used here for both mysql.

Step 1. First of all we take a simple Project in the Netbeans. First i would recommend to go in the Meny Bar -> the select to New Project (shift+ctrl+n) and follow the step and put the required name as we want to use of our application We will use here Struts2_Update application name and then if we you have install the struts framework into the struts the you can select other wise click on finish. later you will need to add the jar library of the struts famework. Link to download the application framework jar click here.Download jar file of this Framework

Step 2. Now first of all we need to a database and a table also will be in that data which have data into that table. Because without data into the table we can't perform the action which we want to use. That table data will be fetched on the jsp page for performing the action.

Step 3. Create a database into the mysql database other wise we can use a single database which we have created as before.

create database R4R_Database;
use database R4R_Database;

Step 4. Create table inside the database.

create table UpdateData
(
id int(4) primary key,
fname varchar(50),
lname varchar(50),
email varchar(50),
addr varchar(50)
);

Above given table we will use in first for fetching the database stored into the table. Now we mannually insert the data into the database.

insert into UpdateData values(1,'Rahul','kumar','rahl@test.com','ghaziabad');

the above query we will use to insert data into the table.

Step 5. Here we will design that page which first fetch table data into the jsp page then we will perform our action using struts.xml mapping file.

FetchData.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<%@ page import="java.util.*,R4R_Pojo.MyBean" %>
<% MyBean b; %>
<body bgcolor="lightyellow">
<center>
    <h1>Struts2 Show The Fetch Record Without Action Using Hibernate Example</h1>
<table width="1000" border="1">
<tr><td><b>SNO</b></td><td><b>SName</b></td><td><b>Country</b></td><td><b>Operation</b></td></tr>

<% 
List l=(List)request.getAttribute("rec");
if(l!=null)
{
Iterator it=l.iterator();
while(it.hasNext())
{
b=(R4R_Pojo.MyBean)it.next();

%>
<tr><td><%= b.getSno() %></td><td><%= b.getSname() %></td><td><%= b.getScountry() %></td><td><a href=update.action?fid=<%= b.getSno() %>>Click Here for Update</a></tr> 
        
<%
}
}

%> 

</table>
</center>
</body>

index.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<META HTTP-EQUIV="Refresh" CONTENT="1;URL=verify.action">

Success.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

Executed successfully....!!!!!
<META HTTP-EQUIV="Refresh" CONTENT="1;URL=verify.action">

EditIntoTable.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page import="java.util.*;" %>

<html>

<body bgcolor="lightyellow">
<center>
<s:form action="updateRecInDB" method="post" name="fom">
    <table bgcolor="pink">
    <h1>Struts2 Show The Fetch Record With Delete Action Using Hibernate Example</h1>
<tr><td>

<s:textfield label="Number" value="%{#application.x}" readonly="true" name="b.sno" />
<s:textfield label="Name" value="%{#application.y}" name="b.sname"/>
<s:textfield label="Country" value="%{#application.z}" name="b.scountry"/>
 
<s:submit value="Update" />

</td>
</tr>

</table>    
    
</s:form>


</center>
</body>
</html>

Step 6. Now we will attatch the hibernate configuration the connectivity of database. For this we need to go into the File menu wizard then select new file and search to hibernate and click on hibernate configuration file and click next and now here select the your database if now showing in the list then click on new connection and here write the name of your database and click on finish.

hibernate cfg file code

<?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="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/hibernate_pro</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <mapping resource="R4R_Pojo/MyBean.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Step 7. Now here we need a another file to completion the action of the hibernate cfg file that is hibernate revenge file. For this we need to go into the File menu wizard then select new file and search to hibernate and click on hibernate revenge file and click next and now here select the table of your database and click on finish.

revenge file code is sow

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="hibernate_pro"/>
  <table-filter match-name="MyBean"/>
</hibernate-reverse-engineering>

Step 8. Now create the two package. one for pojo class and another for the action class. For this we need to go into the File menu wizard then select new file and search to java and click on package and click next and put the name on the required field and click on finish.

Step 9. Now at last we need to use to make pojo class we take the revenge file into our applicaion. For this we need to go into the File menu wizard then select new file and search to hibernate and click on hibernate pojo class file and click next and select the package in which we want to put this and click on finish.

MyBean.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 23 Feb, 2015 8:19:59 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="R4R_Pojo.MyBean" table="MyBean" catalog="hibernate_pro" optimistic-lock="version">
        <id name="sno" type="int">
            <column name="sno" />
            <generator class="assigned" />
        </id>
        <property name="sname" type="string">
            <column name="sname" length="10" />
        </property>
        <property name="scountry" type="string">
            <column name="scountry" length="50" />
        </property>
    </class>
</hibernate-mapping>

MyBean.java

package R4R_Pojo;
// Generated 23 Feb, 2015 8:19:58 PM by Hibernate Tools 4.3.1
/**
 * MyBean generated by hbm2java
 */
public class MyBean  implements java.io.Serializable {
     private int sno;
     private String sname;
     private String scountry;
    public MyBean() {
    }
    public MyBean(int sno) {
        this.sno = sno;
    }
    public MyBean(int sno, String sname, String scountry) {
       this.sno = sno;
       this.sname = sname;
       this.scountry = scountry;
    }
    public int getSno() {
        return this.sno;
    }
    public void setSno(int sno) {
        this.sno = sno;
    }
    public String getSname() {
        return this.sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    public String getScountry() {
        return this.scountry;
    }
    public void setScountry(String scountry) {
        this.scountry = scountry;
    }
}

Step 10. Now we need to take an another java class for performing the action. For this we need to go into the File menu wizard then select new file and search to java and click on java class file put the required name and select package and click on finish.

ApplicationController.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package R4R_Dao;

/**
 *
 * @author sarvesh
 */
import static com.opensymphony.xwork2.Action.SUCCESS;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
import R4R_Pojo.MyBean;
import java.util.Iterator;

public class ApplicationController extends ActionSupport implements ServletRequestAware,ApplicationAware{
private static final long serialVersionUID = 1L;
ApplicationMainOperation ma = new ApplicationMainOperation();
private List<MyBean> recordsFromDB;
        MyBean b;
    public MyBean getB() {
return b;
}
public void setB(MyBean b) {
this.b = b;
}
    //For RequestAware Interface
HttpServletRequest request;
        @Override
public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }
    public HttpServletRequest getServletRequest() {
        return request;
    }
    
    //For Bean, while selecting..
public List<MyBean> getRecordsFromDB()
{
 return this.recordsFromDB;
}
// for ApplicationAware Interface
Map m;
        @Override
    public void setApplication(Map m)
{
this.m=m;
 
    // *******     For select query  ********
public String getRecords()
{
            
recordsFromDB = ma.retrieveRecords();
request.setAttribute("rec", recordsFromDB);
return SUCCESS;
}
         public String getRecordToUpdate()
{
recordsFromDB = ma.retrieveRecord(request.getParameter("fid"));

Iterator<MyBean> it = recordsFromDB.iterator();
while(it.hasNext())
{
  Object o = it.next();
  b = (MyBean)o;
}
       m.put("x",b.getSno());
m.put("y", b.getSname());
m.put("z",b.getScountry());
return SUCCESS;
}
 public String updateRec()
{
ma.upRecord(b);
return SUCCESS;
}      
}

ApplicationMainOperation.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package R4R_Dao;

/**
 *
 * @author sarvesh
 */
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import R4R_Pojo.MyBean;
import org.hibernate.Query;
import org.hibernate.Transaction;
public class ApplicationMainOperation{
    SessionFactory factory = HibernatePlug.getFactory();
Session session = factory.openSession();
MyBean p;
List recList = null;
public List retrieveRecords() {
recList = (List<MyBean>) session.createQuery("from MyBean b").list();
System.out.println("got size"+recList.size());
return recList;
}
public List retrieveRecord(String val) {
 recList = (List<MyBean>) session.createQuery("from MyBean b where b.sno="+val).list();
System.out.println("got size"+recList.size());
 return recList;
}
        public void upRecord(MyBean p) {
Transaction tx = session.beginTransaction();
   Query qry = session.createQuery("update MyBean b set b.sname=?, b.scountry=? where b.sno="+p.getSno());
   qry.setParameter(0,p.getSname());
   qry.setParameter(1,p.getScountry());
            qry.executeUpdate();
            System.out.println("Object updated successfully...");
    tx.commit();
}
}

HibernatePlug.java

package R4R_Dao;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernatePlug 
{
    private static final SessionFactory factory = getSessionFactory();
    public static synchronized SessionFactory getSessionFactory() 
     {
try {    
      Configuration cfg = new Configuration();
      cfg.configure("hibernate.cfg.xml"); 
SessionFactory sessionFactory = cfg.buildSessionFactory();
    System.out.println(" ----------   Factory Object Created  ------------");
       return sessionFactory;
     }catch (Throwable ex) 
                {
                  System.err.println("Initial SessionFactory creation failed." + ex);
  throw new ExceptionInInitializerError(ex);
}
 }
public static SessionFactory getFactory() {
return factory;
}
}

Step 11. Now we need to configure action of the application in the struts.xml file. if should be always in default package.

code of strust.xml file

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <include file="example.xml"/>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default">
        <action name="verify" class="R4R_Dao.ApplicationController" method="getRecords">
            <result name="success">/FetchData.jsp</result>
            <result name="error">/Error.jsp</result>
        </action>
        <action name="update" class="R4R_Dao.ApplicationController" method="getRecordToUpdate">
            <result name="success">/EditIntoTable.jsp</result>
            <result name="error">/Error.jsp</result>
        </action>
        <action name="updateRecInDB" class="R4R_Dao.ApplicationController" method="updateRec">
            <result name="success">/Success.jsp</result>
            <result name="error">/Error.jsp</result>
        </action>
    </package>
</struts>

Step 12. Now build the application and run the application.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!