Hibernate

adplus-dvertising
Complete application Using Insert, Update, Fetch, Delete, Validate Action with Hibernate and Struts
Previous Home Next

Here in the Hibernate tutorial we have learn how to insert, update, delete fetch data using Hibernate. But now we will learn how to make a combined application using all these action. For making these tye of application we used in the project. This type of activity provides to learn how to determine the combined application and how to create the data using all action.

For making the combined application we need to start with the all action study before if we did not done this we can't make to the combined application using all action of the database. If we have done the all action study then we can create the combined application. For this we need to follow the some basic step which can help to develop the application using the all action.

First we need to start the Netbeans the and database also.

Step 1. Now here we will do one thing in the first that is the database creation and table creation.


(a). create database hibernate_pro
(b). create table MyBean
	(
	id int not null primary key,
	sname varchar(50),
	scountry varhcar(50)
	)	

Step 2. Now we will the design part of the application. Here we need to create the 6 jsp page that will be (Main.jsp, DataIntoTable.jsp, EditIntoTable.jsp, Error.jsp, Success.jsp, WelcomeToInsertData.jsp). These file will be create as we required after the action code implementation.

(a). Main.jsp file code:


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

(b). DataIntoTable.jsp


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

<head>
<link rel="stylesheet" type="text/css" href="css/java4s.css" />
<script type="text/javascript">
function deleteRecord()
	{	     
	    document.fom.action="delete.action";
	    document.fom.submit();
	}
function insertRecord()
{	     
    document.fom.action="insertLink.action";
    document.fom.submit();
}	
function editr(val)
{	     
   document.fom.action="update.action?fid="+val;
   document.fom.submit();   
}	
</script>

</head>

<form method="post" name="fom">

<table class="mtable">
<tr><td colspan="5">

<font face="verdana" size="2">
<input type="button" value="insert" onclick="insertRecord()"> 
<input type="button" value="delete" onclick="deleteRecord()"> <br><br>

</font>

</td></tr>

<tr>
<td class="th"><center>+</center></td>
<td class="th"><b>SNO</b></td>
<td class="th"><b>SName</b></td>
<td class="th"><b>Country</b></td>
<td class="th"><b> Ope.</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 class="bord"><input type="checkbox" value="<%= b.getSno() %>" name="rdel"></td>
        <td class="bord"><%= b.getSno() %></td>
        <td class="bord"><%= b.getSname() %></td>
        <td class="bord"><%= b.getScountry() %></td>
        <td class="bord"><a href="javascript:editr('<%= b.getSno()%>')">Edit</a></td>         
        </tr> 
        
<% 		
				
	}	
}

%> 

</table>
</form>

(c). EditIntoTable.jsp


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

<html>

<head>
<link rel="stylesheet" type="text/css" href="css/java4s.css" />

<script type="text/javascript">
function display()
	{	     
	    document.fom.action="verify.action";
	    document.fom.submit();
	}
</script>

</head>

<body>

<s:form action="updateRecInDB" method="post" name="fom"> 	

<table class="mtableu">
<tr>
<td colspan="2">

<input type="button" value="Display Records" onclick="display()"> 

</td></tr>

<tr><td>
			<s:textfield label="Number" value="%{#application.x}" readonly="true" name="b.no" cssClass="bord"/>
			<s:textfield label="Name" value="%{#application.y}" name="b.nam" cssClass="bord"/>
			<s:textfield label="Country" value="%{#application.z}" name="b.ct" cssClass="bord"/>
 
<s:submit value="Update" />

</td>
</tr>
</table>    
    
</s:form>

</body>
</html>

(d). Error.jsp


 <h1>This is an error Page</h1>

e). Success.jsp


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

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

(f). WelcomeToInsertData.jsp


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

<html>

<head>
<link rel="stylesheet" type="text/css" href="css/java4s.css" />

<script type="text/javascript">
function display()
	{	     
	    document.fom.action="verify.action";
	    document.fom.submit();
	}
</script>

</head>

<body>

	<s:form action="insert" name="fom"> 	

<table class="mtableu">
<tr>
<td colspan="2">

<input type="button" value="Display Records" onclick="display()"> 

</td></tr>

<tr><td>
			<s:textfield label="Number" name="b.sno" cssClass="bord"/>
			<s:textfield label="Name" name="b.sname" cssClass="bord"/>
			<s:textfield label="Country" name="b.scountry" cssClass="bord"/>
 
<s:submit value="Insert" />

</td>
</tr>
</table>    
    
</s:form>

</body>
</html>

Step 3. Now we need to add the configuration file into our own application. For this we need to follow the step which we have discussed in our last example.


<?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?zeroDateTimeBehavior=convertToNull</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 4. Now we need to create the revenge file. It will help to create the POJO class.

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

Step 5. Now we need to create the 2 packages.like (R4R_Dao and R4R_Pojo)

Step 6. Now we will create here the Pojo class. by following the step whihc we have discussed in our last example.

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 20 Feb, 2015 1:16:11 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 20 Feb, 2015 1:16:10 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 7. Now we will create tha action part of the application which help us to make action which we want to perform. Now we need to select to package (R4R_Dao)

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.Iterator;
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;
	} 
	
   //*********    For update query  ********
	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;
	}
	
	// ********     Insert method      *********
	public String insertRecord()
	{			
		ma.insertRecord(b);			
		return SUCCESS;
	}
	
	//**********    update in database  **********
	public String updateRec()
	{			
		ma.upRecord(b);			
		return SUCCESS;
	}
	public String deleteRecord()
	{	
		String cv[] = null;
		cv=request.getParameterValues("rdel");		
	 	ma.deleteRecord(cv);			
		return SUCCESS;
	}	
}

ApplicationLinks.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
 */
public class ApplicationLinks{ 
	public String insert()
	{
		return "insert";			
	}
	public String display()
	{
		return "display";			
	}
	
}

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.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import R4R_Pojo.MyBean;

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 insertRecord(MyBean p) {			
		 Transaction tx = session.beginTransaction();	 
	       session.save(p);
	       System.out.println("Object saved successfully.....!!");
	     tx.commit();				
	}
	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();				
	}
	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 8. In the all of the end we need to configure the struts xml file to making the right action which and where we want to perform.

struts.xml


 <!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">/DataIntoTable.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">/Sucess.jsp</result>
            <result name="error">/Error.jsp</result>
        </action>
        
         <action name="insert" class="R4R_Dao.ApplicationController" method="insertRecord">
            <result name="success">/Sucess.jsp</result>
            <result name="error">/Error.jsp</result>
        </action> 
        
        <action name="delete" class="R4R_Dao.ApplicationController" method="deleteRecord">
            <result name="success">/Sucess.jsp</result>
            <result name="error">/Error.jsp</result>
        </action> 
        
         <action name="*Link" class="R4R_Dao.ApplicationLinks" method="{1}">
            <result name="insert">/EditIntoTable.jsp</result>
            <result name="display">/DataIntoTable.jsp</result>           
        </action>
    </package>
</struts>

Step 9. Now we need to run the application by the selecting the project node.

Previous Home Next