Gadgets

Saturday, 12 March 2016

Hibernate web application with CRUD operations using eclipse IDE

Hibernate CRUD operations in Eclipse

Here we have hibernate web application with CRUD operations using eclipse IDE and using Netbeans IDE 
Here I have created a registration form and servlet to insert data into database, and same as I done operations retrieve, update, and delete.
You need to follow the below steps to create hibernate application:
1.      Create the Dynamic web project
2.      Load the required jar files
3.      Create the persistent class
4.      Create the mapping file for persistent class
5.      Create the configuration file
6.      Create the classes that store, retrieve, update, and delete.
7.      Run the application

It is very simple to understand, don’t feel like it is hard and programs are so long.

Read also: 

Project folder structure:


Step 2 : Load the jar files

antlr-2.7.6.jar
asm-attrs.jar
asm.jar
c3p0-0.9.1.jar
cglib-2.1.3.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.6.1.jar
ehcache-1.2.3.jar
ejb3-persistence.jar
hibernate3.jar
jdbc2_0-stdext.jar
jta.jar
log4j-1.2.11.jar
mysql-connector-java-5.1.23-bin.jar
xerces-2.6.2.jar

Step 3 : Create the persistent class

StudentInfo.java

package com.javathub;
public class StudentInfo {
       private int id;
       private String name;
       private String branch;
       private double fee
       public StudentInfo(){            
       }
       public StudentInfo(int id, String name, String branch, double fee) {
              super();
              this.id = id;
              this.name = name;
              this.branch = branch;
              this.fee = fee;
       }
       public int getId() {
              return id;
       }
       public void setId(int id) {
              this.id = id;
       }
       public String getName() {
              return name;
       }
       public void setName(String name) {
              this.name = name;
       }
       public String getBranch() {
              return branch;
       }
       public void setBranch(String branch) {
              this.branch = branch;
       }
       public double getFee() {
              return fee;
       }
       public void setFee(double fee) {
              this.fee = fee;
       }
}

web.xml

<?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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Studentinfo</display-name>
  <welcome-file-list>
    <welcome-file>studentreg.jsp</welcome-file>
  </welcome-file-list> 
</web-app>

Step 4 : Create the hibernate mapping file

File name should be persistent-class-name.hbm.xml

studentinfo.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping>
<class name="com.javathub.StudentInfo" table="student">
<id name="id"/>
<property name="name"/>
<property name="branch"/>
<property name="fee"/>
</class>
</hibernate-mapping>

Step 5: Hibernate configuration file

hibernate.cfg.xml

<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
     <property name="hibernate.connection.url"> jdbc:mysql://localhost/studentdb </property>
    <property name="hibernate.connection.username">studb</property>
   <property name="hibernate.connection.password">12345</property>
   <property name="connection.pool_size"> 1</property>
  
   <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <!-- <property name="hbm2ddl.auto">create</property>
  <property name="show_sql">true</property> -->
   <!-- List of XML mapping files -->
   <mapping resource="studentinfo.hbm.xml"/>
   </session-factory>
</hibernate-configuration>

This line will create auto table creation
<!-- <property name="hbm2ddl.auto">create</property>

Step 6 : Create the forms and servlets based on our requirement

studentreg.jsp

<h1>Student Registration form</h1>
<form action="./StudentController" method="post">
<table>
<tbody>
<tr> <td>Student Id :</td><td><input type="text" name="id"/></td></tr>
<tr> <td>Student Name :</td><td><input type="text" name="name"/></td></tr>
<tr> <td>Branch :</td><td><input type="text" name="branch"/></td></tr>
<tr> <td>Tuition Fee :</td><td><input type="text" name="fee"/></td></tr>
<tr> <td></td><td><input type="submit" value="Save"/></td></tr>

</tbody>

</table>

 StudentController.java

package controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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;
import com.javathub.StudentInfo;
public class StudentController extends HttpServlet {
       private static final long serialVersionUID = 1L;   
    public StudentController() {
        super();      
    } 
       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         
              String name,branch;
              int id=Integer.parseInt(request.getParameter("id"));
              name=request.getParameter("name");
              branch=request.getParameter("branch");
              double fee=Double.parseDouble(request.getParameter("fee"));
              try{         
              Configuration cfg=new Configuration();
              cfg.configure("hibernate.cfg.xml");
             
              SessionFactory sf=cfg.buildSessionFactory();
              Session se=sf.openSession();
             
              Transaction tr=se.beginTransaction();          
              StudentInfo si=new StudentInfo();
              si.setId(id);
              si.setName(name);
              si.setBranch(branch);
              si.setFee(fee);
              se.save(si);
              tr.commit();
              RequestDispatcher rd=request.getRequestDispatcher("welcomepage.jsp");
              rd.forward(request, response);          
              }
              catch(Exception ex){
                     System.out.println(ex);                 
              }            
              finally{
                     System.out.close();
              }     
       }
}

 welcomepage.jsp

<h1>Welcome</h1>
<%
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");

SessionFactory sf=cfg.buildSessionFactory();
Session se=sf.openSession();

Transaction tr=se.beginTransaction();
Query q=se.createQuery("from StudentInfo");
StudentInfo si=new StudentInfo();
ArrayList al=new ArrayList();
al=(ArrayList)q.list();
Iterator i=al.iterator();
       %>
       <table border="1">
       <thead>
       <tr>
       <th>Student Id</th>
       <th>Student name</th>
       <th>Student branch</th>
       <th>Student fee</th>
       <th>Edit</th>
       <th>Delete</th>
       </tr>
       </thead>
       <tbody>
       <%while(i.hasNext()){
       si=(StudentInfo)i.next();        
       %>
       <tr>
       <td><%= si.getId()%></td>
       <td><%= si.getName()%></td>
       <td><%= si.getBranch()%></td>
       <td><%= si.getFee()%></td>
       <td><a href="edit.jsp?id=<%= si.getId()%>">Edit</a></td>
       <td><a href="delete.jsp?id=<%= si.getId()%>">Delete</a></td>
       </tr>
       </tbody>
       <%
}
%>
       </table>

Delete.jsp

<%
int id=Integer.parseInt(request.getParameter("id"));
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");

SessionFactory sf=cfg.buildSessionFactory();
Session se=sf.openSession();

Transaction tr=se.beginTransaction();
Query qu=se.createQuery("delete StudentInfo where id=:id");
 qu.setParameter("id", id);
int i=qu.executeUpdate();
tr.commit();
if(i>0){
       response.sendRedirect("welcomepage.jsp?msg=Successfully Deleted.....!");  
}
else{
       response.sendRedirect("welcomepage.jsp?msg=Student Details are not available.....!");   
}
%>

edit.jsp

<h1>Welcome</h1>
<%
int id=Integer.parseInt(request.getParameter("id"));
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");

SessionFactory sf=cfg.buildSessionFactory();
Session se=sf.openSession();

Transaction tr=se.beginTransaction();
Query q=se.createQuery("from StudentInfo where id=:id");
q.setParameter("id", id);

StudentInfo si=new StudentInfo();

ArrayList al=new ArrayList();
al=(ArrayList)q.list();
Iterator i=al.iterator();
while(i.hasNext()){
       si=(StudentInfo)i.next();        
       %>    
       <form action="./StudentUpdate" method="post">
<table>
<tbody>
<tr> <td>Student Id :</td><td><input type="text" name="id" value="<%= si.getId()%>" readonly=""/></td></tr>
<tr> <td>Student Name :</td><td><input type="text" name="name" value="<%= si.getName()%>"/></td></tr>
<tr> <td>Branch :</td><td><input type="text" name="branch" value="<%= si.getBranch()%>"/></td></tr>
<tr> <td>Tuition Fee :</td><td><input type="text" name="fee" value="<%= si.getFee()%>"/></td></tr>
<tr> <td></td><td><input type="submit" value="Update"/></td></tr>
</tbody>
</table>
</form>      
       <%
}
%>

StudentUpdate.java

package controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.javathub.StudentInfo;
public class StudentUpdate extends HttpServlet {
       private static final long serialVersionUID = 1L;
    public StudentUpdate() {
        super();
     }
       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         
              String name,branch;
              int id=Integer.parseInt(request.getParameter("id"));
              name=request.getParameter("name");
              branch=request.getParameter("branch");
              double fee=Double.parseDouble(request.getParameter("fee"));
              try{         
              Configuration cfg=new Configuration();
              cfg.configure("hibernate.cfg.xml");
             
              SessionFactory sf=cfg.buildSessionFactory();
              Session se=sf.openSession();            
              Transaction tr=se.beginTransaction();
              Query q=se.createQuery("update StudentInfo set name=:name, branch=:branch, fee=:fee where id=:id");
              q.setParameter("id", id);
              q.setParameter("name", name);
              q.setParameter("branch", branch);
              q.setParameter("fee", fee);
              int i=q.executeUpdate();         
              tr.commit();
              if(i>0){
                     RequestDispatcher rd=request.getRequestDispatcher("welcomepage.jsp");
                     rd.forward(request, response);
              }            
              }
              catch(Exception ex){
                     System.out.println(ex);                 
              }            
              finally{
                     System.out.close();
              }            
       }            
       }

Output screens:



                  
Any doubts regarding this tutorial comment below

No comments:

Post a Comment