Hibernate

adplus-dvertising
Update data into the database Using Hibernate and Servlet
Previous Home Next

Here we will discuss how to update data into the database table without go in the database. Yes it can be possible when we work with the hibernate. For this we will take as we discussed in the last example how to fetch data form the database table data into the jsp page.

Here in the Hibernate we can update the data which we inserted into the database. It can be done through the some basic step as we discussed in our last session of the project example of the hibernate. So now here we will create as we done before and we will show the code to implement only here.

Step 1. take a project.

Step 2. create a jsp page for input data.

InsertData.jsp


<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Hibernate Application Using Servlet</title>
    </head>
<body>
        <pre>
        <form action="MyServlet" method="post">
        First Name      <input type="text" name="fist_name"/>
        Last Name       <input type="text" name="last_name"/>
        Salary          <input type="text" name="sal"/>
        
        
                        <input type="submit" value="Submit"/>
      </form>
        </pre>
    </body>   
</html>

Step 3. create a table in the database. Remember which database you selected on the time of the project taking all table will be created into the same database. Now we here we will use the hibernate_pro database.


1. create table InsertData001
   (
     id int not null auto_increment primary key,
     fname varchar(50),
     lname varchar(50),
     sal int(50));

Step 4. Take a package type the name of the package r4r.

Step 5. create a Hibernate reverse engineering file as we discussed in our last example.

hibernate.reveng.xml


<?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="InsertData001"/>
</hibernate-reverse-engineering>

Step 6. create a POJO class it is also we discussed in out last session.(Note that POJO class must be creted into the package)

InsertData001.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 19 Dec, 2014 10:02:18 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="r4r.InsertData001" table="InsertData001" catalog="hibernate_pro" optimistic-lock="version">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="fname" type="string">
            <column name="fname" length="50" />
        </property>
        <property name="lname" type="string">
            <column name="lname" length="50" />
        </property>
        <property name="sal" type="java.lang.Integer">
            <column name="sal" />
        </property>
    </class>
</hibernate-mapping>

InsertData001.java


package r4r;
public class InsertData001  implements java.io.Serializable {
     private Integer id;
     private String fname;
     private String lname;
     private Integer sal;

    public InsertData001() {
    }

    public InsertData001(String fname, String lname, Integer sal) {
       this.fname = fname;
       this.lname = lname;
       this.sal = sal;
    }
   
    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFname() {
        return this.fname;
    }
    
    public void setFname(String fname) {
        this.fname = fname;
    }
    public String getLname() {
        return this.lname;
    }
    
    public void setLname(String lname) {
        this.lname = lname;
    }
    public Integer getSal() {
        return this.sal;
    }
    
    public void setSal(Integer sal) {
        this.sal = sal;
    }
}

Step 7. Now we create a servlet file for making the action to perform the value into the database.

InsertData.java


package r4r;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class InsertData extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {
        response.setContentType("text/html;charset=UTF-8");
        String fname,lname,sal;
        fname = request.getParameter("fname");
        lname = request.getParameter("lname");
        sal = request.getParameter("sal");
        SessionFactory sf = new Configuration().configure().buildSessionFactory();
        Session s = sf.openSession();
        Transaction tr = s.beginTransaction();
        InsertData001 id = new InsertData001(fname, lname, Integer.parseInt(request.getParameter("sal")));
        s.save(id);
        tr.commit();
        s.close();
        
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
           
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet InsertData</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Welcome " + fname +   "You have inserted the data</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

        @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }

}

Step 8. Now build and run the application.

Step 9. create a hibernate.util file for making the connection between database and application.

HibernateUtil.java


package r4r;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) 
        {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Step 9. Now we need to create a jsp page to update the data. In this we fetch the data form the database in a table and perform the action update.

FetchTableData.jsp


<%@include file="menu.jsp" %>
<%@page import="org.hibernate.criterion.Restrictions" %>
<%@page import="org.hibernate.*" %>
<body>
    <table width="900" border="2"><tr><th>Sr. No</th><th>First Name</th><th>Last Name</th>
	<th>Age</th><th>Last Update</th><th>Operation</th></tr>
        <%
        SessionFactory sf = r4r.HibernateUtil.getSessionFactory();
        Session s = sf.openSession();
        Transaction tr = s.beginTransaction();
        Criteria cr = s.createCriteria(r4r.InsertData.class);
        java.util.List<r4r.InsertData> ds = cr.list();
        for(r4r.InsertData dd : ds)
        {
            out.println("<tr><td>"+dd.getId()+"<td>"+dd.getFirstName()+"<td>"
			+dd.getLastName()+"<td>"+dd.getAge()+"<td>"+dd.getLastUpdate()+
                    "<td><a href=Delete.jsp?t="+dd.getId()+">Delete</a> "+"
			/ <a href=Update.jsp?t="+dd.getId()+">Update</a>");
        }
        %>   
    </table>

Step 11. Create a jsp page to perform the action of update.

Update.jsp


 <%@page import="org.hibernate.criterion.Restrictions" %>
<%@page import="org.hibernate.*" %>
<%
    int n = Integer.parseInt(request.getParameter("t"));
    String fn = request.getParameter("t2");
    String ln = request.getParameter("t3");
    
    SessionFactory sf = r4r.HibernateUtil.getSessionFactory();
    Session s = sf.openSession();
    Transaction tr = s.beginTransaction();
    r4r.InsertData001 r = (r4r.InsertData001)s.get(r4r.InsertData001.class, n);
    if(fn!=null)
    {
        int sal = Integer.parseInt(request.getParameter("t4"));
        r.setFname(fn);
        r.setLname(ln);
        r.setSal(sal);
        s.update(r);
        tr.commit();
        response.sendRedirect("FetchTableData.jsp");
    }
%>
<form action="Update.jsp" method="post">
    <h3><pre>
            Id  :   <%=r.getId()%> <input type="hidden" name="t" value="<%=r.getId()%>"/>
   
    First Name  :   <input type="text" name="t2" size="20" value="<%=r.getFname()%>" /> 

      Last Name :   <input type="text" name="t3" size="20" value="<%=r.getLname()%>" /> 

      Salary    :   <input type="text" name="t4" size="40" value="<%=r.getSal()%>"/>

                       <input type="submit" value="update">

        </pre>
    </h3>
</form>

Step 11. Now run this file.

Previous Home Next