.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> General >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Update records using hibernate

Posted By:satyapriyanayak       Posted Date: January 02, 2015    Points: 200    Category: General    URL: http://www.dotnetspark.com  

In this article we will know how to update records using hibernate.
 

Creating client of hibernate (to update data)

1.Create an object of org.hibernate.cfg.configuration by using its default constructor.
2.Call configure () of configuration to initialize hibernate.
3.Create an object of org.hibernate.session factory by using buildsessionfactory() of configuration.
4.Create an object of org.hibernate.session by using openSession() of sessionFactory.
5.Create the object of org.hibernate.transaction by using beginTransaction() method of session
6.Find the required object of Pojo by using class name and the variable representing primary key into the get() method of session.
7.Change the values of variables by using the required setter() method of Pojo.
8.Complete the transaction by using commit() method of transaction.
9.Save the changes by using update() method of session.This method accepts object name of  Pojo.

Installation of hibernate

1.Get the binary distribution file of hibernate (hibernate-distribution-3.3.1.ga-dist.zip) and extract it into any folder.Get it from the below url http://sourceforge.net/projects/hibernate/files/hibernate3/3.3.1.GA/hibernate-distribution-3.3.1.GA-dist.zip/download

2.Search for all .jar files present in extracted folder and make those files available in lib folder of the context. The lib folder must be created in the WEB-INF folder.

Creation of a context file

Create any folder in any drive as (E:\hybernate). Inside that folder store your .jsp files. Give the Context path name as javahibernate and docBase as E:\hybernate, here docBase means the total path where we are storing our .jsp files and .html files. Store the java bean file inside 'classes' folder of the context for predefined context (root) the classes folder required to be created inside the WEB-INF folder. These changes are done in the server.xml file, which is present in (E:\Program Files\Apache Software Foundation\Tomcat 6.0\conf) directory.

Table creation in Mysql database

Test.sql file

-- phpMyAdmin SQL Dump
-- version 3.2.4
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Sep 28, 2014 at 11:46 AM
-- Server version: 5.1.41
-- PHP Version: 5.3.1

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `test`
--

-- --------------------------------------------------------

--
-- Table structure for table `emp`
--

CREATE TABLE IF NOT EXISTS `emp` (
  `empno` int(11) NOT NULL,
  `ename` varchar(255) NOT NULL,
  `sal` int(11) NOT NULL,
  PRIMARY KEY (`empno`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `emp`
--

INSERT INTO `emp` (`empno`, `ename`, `sal`) VALUES
(1, 'Raj', 10000),
(2, 'Ravi', 20000),
(3, 'Rahul', 30000);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Creation of java bean

1.Create a class in a package as the bean class.
2.Provide required variables as the properties.
3.Provide setter and getter methods for each variables.
4.Store the package folder inside classes folder.
5.Compile the file as any ordinary java file.

Create a package folder named as mypack inside classes folder of the context (E:\hybernate\WEB-INF\classes). Inside mypack folder place the Emp.java bean file.

Emp.java

package mypack;
/*
  a BEAN FOR HIBERNATE MAPPING
*/
public class Emp {
    
    private Integer empno;
    private String ename;
    private Double sal;
    
    public Emp() {}

    public Emp(int no,String nm,double sl)
    {
        this.empno=no;
        this.ename=nm;
        this.sal=sl;
    }
    
    public Integer getEmpno() {
        return empno;
    }
    public void setEmpno(Integer empno) {
        this.empno = empno;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public Double getSal() {
        return sal;
    }
    public void setSal(Double sal) {
        this.sal = sal;
    }
}

Compile

Javac Emp.java
 

index.html


<html>
<body>
<h1><a href="./Display.jsp">Show Employee</a></h1>
</body>
</html>

Display.jsp

<%@ page import="java.util.*,mypack.*,org.hibernate.*,org.hibernate.cfg.*" %>
<%! int id;double sal; String name; Session session1 = null; %>
<body>
<table width="220" border="1">
<form action="./delEmp.jsp">
<tr><th>NUMBER</th><th>NAME</th><th>SALARY</th></tr>        
<%
Configuration cf=new Configuration();
cf.configure();
SessionFactory sf = cf.buildSessionFactory();
session1 =sf.openSession();
//Using from Clause
String SQL_QUERY ="from Emp";
Query query = session1.createQuery(SQL_QUERY);
Iterator it=query.iterate();
while(it.hasNext())
{
Emp e=(Emp)it.next();
id=e.getEmpno();
name=e.getEname();
sal=e.getSal();        
%>        
<tr>
<td><%=id%></td>
<td><%=name%></td>
<td><%=sal%></td>
<td><a href="./updEmp.jsp?a=<%=id%>&b=<%=name%>&c=<%=sal%>">Edit</a></td>
<td><input type="checkbox" value="<%=id%>" name="c1"></td>
</tr>
<%
}
session1.close();
%>
<tr><td colspan="5" align="right"><input type="submit" value="delete"></td></tr>
</form>
</table>
</body>
</html>


updEmp.jsp

Store all .jsp files inside the context folder (E:\hybernate)

<%@ page import="java.util.*,mypack.*,org.hibernate.Session,org.hibernate.SessionFactory,org.hibernate.Transaction,org.hibernate.cfg.Configuration" %>

<body>
<%
String num=request.getParameter("a");
String  name=request.getParameter("b");
String sal=request.getParameter("c");
String sub=request.getParameter("s1");
int empno=0;
double salary=0;
if(sub != null)
{
 empno=Integer.parseInt(num);
salary=Double.parseDouble(sal);
try
{
Configuration cf=new Configuration();
cf.configure();
SessionFactory fact = cf.buildSessionFactory();
Session sess = fact.openSession();
Transaction tr = sess.beginTransaction();
Emp e = (Emp)sess.get(Emp.class,empno);
e.setEname(name);
e.setSal(salary);
tr.commit();
sess.update(e);
sess.close();
out.println("<h1>Updated successfully!</h1>");
}
catch(Exception e)
{
System.out.println("e="+e.getMessage());
}

}
%>
<form name="f1">
  <table width="371" border="1">
    <tr>
      <th> Emp No </th>
      <td><input name="a" type="text" value="<%= num %>" onFocus="this.blur()">
      </td>
    </tr>
    <tr>
      <th>Emp Name </th>
      <td><input name="b" type="text" value="<%= name %>" ></td>
    </tr>
    <tr>
      <th>Salary </th>
      <td><input name="c" type="text" value="<%= sal %>"></td>
    </tr>
   <tr>
      <th colspan="2"><input type="submit"  name="s1" value="Save" >
      </th>
    </tr>
  </table>
</form>
</body>
</html>

Place two files emp.hbm and hibernate.cfg files inside classes folder of the context. Give the .hbm file name as same as table name.Here in emp.hbm emp is the table name.

emp.hbm file

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="mypack.Emp" table="emp">
       <id name="empno" type="int" column="empno" >
       <generator class="assigned"/>       
      </id>

      <property name="ename">
         <column name="ename" />
      </property>
      <property name="sal">
        <column name="sal"/>
      </property>
      </class>
</hibernate-mapping>

hibernate.cfg file

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//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/test</property>
      <property name="hibernate.connection.username">root</property>
      <property name="hibernate.connection.password"></property>
      <property name="hibernate.connection.pool_size">10</property>
      <property name="show_sql">true</property>
      <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
      <property name="hibernate.hbm2ddl.auto">update</property>
      <!-- Mapping files -->
      <mapping resource="emp.hbm.xml"/>    
</session-factory>
</hibernate-configuration>

Note: - Here test is the database name which we have created in the mysql database.

Running the application

Run the tomcat and start Mysql database then write the below line in the Url
http://localhost:8081/javahibernate/

Here javahibernate is the Context path, which we mentioned in the server.xml file, which is present in (E:\Program Files\Apache Software Foundation\Tomcat 6.0\conf) directory.


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend