Hibernate

adplus-dvertising
Delete data from the database table Using Hibernate and JSP
Previous Home Next

In the session of the Hibernate and struts2 integration tutorial we will learn how to delete 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 famework. For making on this application we need to go through the some basic step which is discuessed below:

For making these type of application we need to use any ide like as netbeans or it can be eclipes. Database will used here for both mysql. Here we need to fetch data from the database so we need to learn how to fetch data from the database. For this we need to go through the application example click here.

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 _Delete 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 strus 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 DeleteData
(
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 datbase.


 insert into DeleteData 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 strust.xml mapping file.

DeletePage.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 With Delete 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=delete.action?rdel=<%= b.getSno() %>>Delete</a></tr> 
        
<% 		
				
	}	
}

%> 

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

index.jsp


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

Success.jsp


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

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 finsh

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 application. 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.java


package R4R_Pojo;
// Generated 25 Feb, 2015 1:14:42 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;
    }




}

MyBean.hbm.java


  <?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 25 Feb, 2015 1:14:43 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>

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;

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 deleteRecord()
	{	
		String cv[] = null;
		cv=request.getParameterValues("rdel");		
	 	ma.deleteRecord(cv);			
		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 void deleteRecord(String cv[]) {	
		Transaction tx = session.beginTransaction();	
		for(int i=0;i<cv.length;i++)
		{
			Query qry = session.createQuery("delete from MyBean b where b.sno="+cv[i]);			 
			qry.executeUpdate();
		}
		System.out.println("Object(s) deleted 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>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default">
        <action name="verify" class="R4R_Dao.ApplicationController" method="getRecords">
            <result name="success">/DeletePage.jsp</result>
            <result name="error">/Error.jsp</result>
        </action>
       <action name="delete" class="R4R_Dao.ApplicationController" method="deleteRecord">
            <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.

Previous Home Next