Working with Hibernate - Display , Insert, Update and Delete in JAVA

Hibernate

 
It is a framework to implement object relational mapping. It provides the facility to persist the state of an object. Whenever a program creates an object of a class then the state of the object can be available until the program needs it again. It helps to keep the state of an object after the exit of the creator program. ORM is a mechanism to store the state of an object into relational storage (DBMS). If the program uses jdbc then the program must know the name of the table and columns to store the values of the variables through SQL commands. The user of hibernate need not know the table and column name. The user of hibernate uses only an object of the classes. Each record available in the table becomes an object in the program.
 

Architecture of Hibernate

 
Architecture of hibernate 
 
Javabean/Pojo
 
This is a class whose objects need to be persisted. The user application creates the objects to store its states into the permanent storage. The user application can change, fetch or remove the state of the object at any time. This class contains a set of variables to represent state and their corresponding setter and getter methods.
 
Mapping
 
This is a set of XML files to establish a relation between pojo and a table of the dbms. It maps the class name with a table name and a variable name with a column name.
 
Configuration
 
This is an XML file that contains information about DBMS and mapping files. This files also contains the name of the dialect classes to convert HQL (Hibernate Query Language) into SQL. Hibernate provides different dialect classes for different DBMS.
 
Hibernate API
 
This is a set of classes and interfaces available from Hibernate to establish a connection with the DBMS. The user program uses this API to configure Hibernate and to send HQL. The dialect classes present in this API send the corresponding HQL to the DBMS.
 
User
 
This is a program or user interface available to end-users. It uses the Hibernate API to configure the API and uses Pojo or javabean to keep the state of the objects intact.
 

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 the lib folder of the context. The lib folder must be created in the WEB-INF folder.

Configuration of Hibernate

 
Create a file named hibernate.cfg.xml inside the classes folder. Use a property tag to specify information about the DBMS, dialect class and mapping files.
 
Tips
 
Search for hibernate.cfg.xml inside the extracted folder of hibernate. Copy any of these files and make it available inside the classes folder.
 
hibernate.cfg.xml file
  1. <?xml version='1.0' encoding='utf-8'?>    
  2. <!DOCTYPE hibernate-configuration PUBLIC    
  3. "-//Hibernate/Hibernate Configuration DTD//EN"    
  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">    
  5. <hibernate-configuration>    
  6. <session-factory>    
  7.       <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>    
  8.       <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>    
  9.       <property name="hibernate.connection.username">root</property>    
  10.       <property name="hibernate.connection.password"></property>    
  11.       <property name="hibernate.connection.pool_size">10</property>    
  12.       <property name="show_sql">true</property>    
  13.       <property name="dialect">org.hibernate.dialect.MySQLDialect</property>    
  14.       <property name="hibernate.hbm2ddl.auto">update</property>    
  15.       <!-- Mapping files -->    
  16.       <mapping resource="emp.hbm.xml"/>          
  17.     
  18. </session-factory>    
  19. </hibernate-configuration>   
Here the database is mysql
 
The database name in mysql - test
 
The table name is emp
 

Creating hibernate POJO or JavaBean

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

Creating hibernate mapping table

  1. Create a file inside the classes folder having the following naming convention classname.hbm.xml
     
    Tips

    Search for any. hbm.xml files inside the extracted folder of Hibernate. Copy any of the files to inside the classes folder of the context. Remove all the tags present inside

    <hibernate-mapping> and </hibernate-mapping>
  2. Provide the tags to the map class name with the table name.
  3. Provide the tags to specify the name of the primary key present in the table with the name of the variable present in the class.
  4. Supply the name of the .hbm file in hibernate.cfg.xml file
emp.hbm file
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping>  
  6.   <class name="mypack.Emp" table="emp">  
  7.                <id name="empno" type="int" column="empno" >  
  8.                <generator class="assigned"/>             
  9.               </id>  
  10.               <property name="ename">  
  11.                          <column name="ename" />  
  12.               </property>  
  13.               <property name="sal">  
  14.                         <column name="sal"/>  
  15.               </property>  
  16.               </class>  
  17. </hibernate-mapping>  

To Display Records

 
Creating a client of Hibernate (to select or display)
  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 an object of org.hibernate.Query by supplying the required HQL into the createQuery() method of the session.
  6. Create a reference to java.util.Iterator by using Iterate() method of the query.
  7. Fetch the object of POJO by using hasNext() method and next() method of iterator.
Creation of a context file
 
Create any folder in any drive ie (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. Store the java bean file inside the 'classes' folder of the context for the predefined context (root) of 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
  1. -- phpMyAdmin SQL Dump    
  2. -- version 3.2.4    
  3. -- http://www.phpmyadmin.net    
  4. -- Host: localhost    
  5. -- Generation Time: Sep 28, 2011 at 11:46 AM    
  6. -- Server version: 5.1.41    
  7. -- PHP Version: 5.3.1    
  8. SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";    
  9. /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;    
  10. /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;    
  11. /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;    
  12. /*!40101 SET NAMES utf8 */;    
  13. --    
  14. -- Database: `test`    
  15. --    
  16. --    
  17. -- Table structure for table `emp`    
  18. --    
  19. CREATE TABLE IF NOT EXISTS `emp` (    
  20.   `empno` int(11) NOT NULL,    
  21.   `ename` varchar(255) NOT NULL,    
  22.   `sal` int(11) NOT NULL,    
  23.   PRIMARY KEY (`empno`)    
  24. ) ENGINE=MyISAM DEFAULT CHARSET=latin1;    
  25. -- Dumping data for table `emp`    
  26. INSERT INTO `emp` (`empno`, `ename`, `sal`) VALUES    
  27. (1, 'Raj', 10000),    
  28. (2, 'Ravi', 20000),    
  29. (3, 'Rahul', 30000);    
  30. /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;    
  31. /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;    
  32. /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;    
Creation of java bean
  1. Create a class in a package as the bean class.
  2. Provide the required variables as the properties.
  3. Provide setter and getter methods for each variable.
  4. Store the package folder inside the classes folder.
  5. Compile the file as any ordinary java file.
Create a package folder named as mypack inside the classes folder of the context (E:\hybernate\WEB-INF\classes). Inside the mypack folder place the Emp.java bean file.
 
Emp.java 
  1. package mypack;  
  2. /* 
  3.   a BEAN FOR HIBERNATE MAPPING 
  4. */  
  5. public class Emp {      
  6.     private Integer empno;  
  7.     private String ename;  
  8.     private Double sal;              
  9.     public Emp() {}    
  10.     public Emp(int no,String nm,double sl)  
  11.     {  
  12.         this.empno=no;  
  13.         this.ename=nm;  
  14.         this.sal=sl;  
  15.     }      
  16.     public Integer getEmpno() {  
  17.         return empno;  
  18.     }  
  19.     public void setEmpno(Integer empno) {  
  20.         this.empno = empno;  
  21.     }    
  22.     public String getEname() {  
  23.         return ename;  
  24.     }    
  25.     public void setEname(String ename) {  
  26.         this.ename = ename;  
  27.     }    
  28.     public Double getSal() {  
  29.         return sal;  
  30.     }  
  31.     public void setSal(Double sal) {  
  32.         this.sal = sal;  
  33.     }  
  34. }  
Compile
 
Javac Emp.java
 
complie java file
 
showEmp.jsp
 
Store all .jsp files inside the context folder (E:\hybernate)
  1. <%@ page import="java.util.*,mypack.*,org.hibernate.*,org.hibernate.cfg.*" %>  
  2. <%! int id;double sal; String name; Session session1 = null; %>  
  3. <body>  
  4. <table width="220" border="1">  
  5. <tr><th>NUMBER</th><th>NAME</th><th>SALARY</th></tr>                       
  6. <%  
  7. Configuration cf=new Configuration();  
  8. cf.configure();  
  9. SessionFactory sf = cf.buildSessionFactory();  
  10. session1 =sf.openSession();  
  11. //Using from Clause  
  12. String SQL_QUERY ="from Emp";  
  13. Query query = session1.createQuery(SQL_QUERY);  
  14. Iterator it=query.iterate();  
  15. while(it.hasNext())  
  16. {  
  17. Emp e=(Emp)it.next();  
  18. id=e.getEmpno();  
  19. name=e.getEname();  
  20. sal=e.getSal();              
  21. %>                    
  22. <tr>  
  23. <td><%=id%></td>  
  24. <td><%=name%></td>  
  25. <td><%=sal%></td>  
  26. </tr>  
  27. <%  
  28. }  
  29. session1.close();  
  30. %>  
  31. </table>  
  32. </body>  
  33. </html>  
Place the two files emp.hbm and hibernate.cfg inside the classes folder of the context. Give the .hbm file name as the same table name. Here in emp.hbm emp is the table name.
 
emp.hbm file
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping>  
  6.   <class name="mypack.Emp" table="emp">  
  7.                <id name="empno" type="int" column="empno" >  
  8.                <generator class="assigned"/>             
  9.               </id>  
  10.   
  11.               <property name="ename">  
  12.                          <column name="ename" />  
  13.               </property>  
  14.               <property name="sal">  
  15.                         <column name="sal"/>  
  16.               </property>  
  17.               </class>  
  18. </hibernate-mapping>  
hibernate.cfg file
  1. <?xml version='1.0' encoding='utf-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3. "-//Hibernate/Hibernate Configuration DTD//EN"  
  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5. <hibernate-configuration>  
  6. <session-factory>  
  7.       <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
  8.       <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>  
  9.       <property name="hibernate.connection.username">root</property>  
  10.       <property name="hibernate.connection.password"></property>  
  11.       <property name="hibernate.connection.pool_size">10</property>  
  12.       <property name="show_sql">true</property>  
  13.       <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
  14.       <property name="hibernate.hbm2ddl.auto">update</property>  
  15.       <!-- Mapping files -->  
  16.       <mapping resource="emp.hbm.xml"/>       
  17. </session-factory>  
  18. </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/showEmp.jsp
 
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.
 
Output
 
display recode using hibernet
 
To Insert Data
 
Follow the above process of "To Display Records" and make the changes which I list below:
 
Creating a client of Hibernate
 
First four steps are the same as "Creating client of hibernate (to select or display)"
  1. Create the object of Pojo and supply a value to the variable by using the constructor or by calling setter methods.
  2. Supply the object of Pojo into the save() method of a session.
  3. Use  theflush() method of a session to commit the changes.
Now after compilation of Emp.java do following:
 
index.html
  1. <html>  
  2.    <body>  
  3.       <h1><a href="./addEmp.jsp">Add Employee</a></h1>  
  4.    </body>  
  5. </html>  
addEmp.jsp
 
Store all .jsp files inside the context folder (E:\hybernate)
  1. <!-- A jsp to insert record through hibernate -->  
  2. <%@ page import="mypack.*,org.hibernate.*,org.hibernate.cfg.*" %>  
  3. <%!  
  4. int empno;double salary;String name; Session session1 = null;  
  5. %>  
  6. <body>  
  7. <%  
  8. String num1=request.getParameter("t1");  
  9. if(num1 != null)  
  10. {  
  11. empno=Integer.parseInt(num1);  
  12. name=request.getParameter("t2");  
  13. String sal=request.getParameter("t3");  
  14. salary=Integer.parseInt(sal);  
  15. try  
  16. {  
  17. Configuration cf=new Configuration();  
  18. cf.configure();  
  19. SessionFactory sessionFactory = cf.buildSessionFactory();  
  20. session1 =sessionFactory.openSession();  
  21. Emp e=new Emp(empno,name,salary);  
  22. session1.save(e);  
  23. session1.flush();  
  24. session1.close();  
  25. out.println("<h1>Data Inserted Successfully</h1>");  
  26. }  
  27. catch(Exception e)  
  28. {  
  29. System.out.println("e="+e.getMessage());  
  30. }  
  31. }  
  32. %>  
  33.   
  34. <form>  
  35.   <table width="352" border="1">  
  36.     <tr>  
  37.       <th>Emp Number</th>  
  38.       <td><input name="t1" type="text"></td>  
  39.     </tr>  
  40.     <tr>  
  41.       <th> Name </th>  
  42.       <td><input name="t2" type="text"></td>  
  43.     </tr>  
  44.     <tr>  
  45.       <th>Salary </th>  
  46.       <td><input name="t3" type="text"></td>  
  47.     </tr>  
  48.     <tr>  
  49.       <th colspan="2"><input type="submit"value="Submit" >  
  50.       </th>  
  51.     </tr>  
  52.   </table>  
  53. </form>  
  54. </body>  
  55. </html>  
Now Run 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.
 
Output
 
insert recorde using hibernate
 
To Update Data
 
Follow the above process of "To Display Records" and made changes which I list below:
 
Creating a client of Hibernate
 
First four steps are the same as "Creating client of hibernate (to select or display)"
  1. Create the object of org.hibernate.transaction by using the beginTransaction() method of session
  2. Find the required object of Pojo by providing its class name and the variable representing the primary key into the get() method of a session.
  3. Change the values of variables by using the required setter() method of Pojo.
  4. Complete the transaction by using commit() method of transaction.
  5. Save the changes by using the update() method of a session. This method accepts object name of Pojo.
Now after compilation of Emp.java do following:
 
index.html
  1. <html>  
  2.    <body>  
  3.       <h1><a href="./Display.jsp">Show Employee</a></h1>  
  4.    </body>  
  5. </html>  
Display.jsp
  1. <%@ page import="java.util.*,mypack.*,org.hibernate.*,org.hibernate.cfg.*" %>  
  2. <%! int id;double sal; String name; Session session1 = null; %>  
  3. <body>  
  4. <table width="220" border="1">  
  5. <form action="./delEmp.jsp">  
  6. <tr><th>NUMBER</th><th>NAME</th><th>SALARY</th></tr>                       
  7. <%  
  8. Configuration cf=new Configuration();  
  9. cf.configure();  
  10. SessionFactory sf = cf.buildSessionFactory();  
  11. session1 =sf.openSession();  
  12. //Using from Clause  
  13. String SQL_QUERY ="from Emp";  
  14. Query query = session1.createQuery(SQL_QUERY);  
  15. Iterator it=query.iterate();  
  16. while(it.hasNext())  
  17. {  
  18. Emp e=(Emp)it.next();  
  19. id=e.getEmpno();  
  20. name=e.getEname();  
  21. sal=e.getSal();              
  22. %>                    
  23. <tr>  
  24. <td><%=id%></td>  
  25. <td><%=name%></td>  
  26. <td><%=sal%></td>  
  27. <td><a href="./updEmp.jsp?a=<%=id%>&b=<%=name%>&c=<%=sal%>" temp_href="./updEmp.jsp?a=<%=id%>&b=<%=name%>  
  28. c=<%=sal%>">Edit</a></td>  
  29. <td><input type="checkbox" value="<%=id%>" name="c1"></td>  
  30. </tr>  
  31. <%|  
  32. }  
  33. session1.close();  
  34. %>  
  35. <tr><td colspan="5" align="right"><input type="submit" value="delete"></td></tr>  
  36. </form>  
  37. </table>  
  38. </body>  
  39. </html>  
updEmp.jsp
 
Store all .jsp files inside the context folder (E:\hybernate)
  1. <%@ page import="java.util.*,mypack.*,org.hibernate.Session,org.hibernate.SessionFactory,org.hibernate.Transaction,org.hibernate.cfg.Configuration" %>  
  2. <body>  
  3. <%  
  4. String num=request.getParameter("a");  
  5. String  name=request.getParameter("b");  
  6. String sal=request.getParameter("c");  
  7. String sub=request.getParameter("s1");  
  8. int empno=0;  
  9. double salary=0;  
  10. if(sub != null)  
  11. {  
  12. empno=Integer.parseInt(num);  
  13. salary=Double.parseDouble(sal);  
  14. try  
  15. {  
  16. Configuration cf=new Configuration();  
  17. cf.configure();  
  18. SessionFactory fact = cf.buildSessionFactory();  
  19. Session sess = fact.openSession();  
  20. Transaction tr = sess.beginTransaction();  
  21. Emp e = (Emp)sess.get(Emp.class,empno);  
  22. e.setEname(name);  
  23. e.setSal(salary);  
  24. tr.commit();  
  25. sess.update(e);  
  26. sess.close();  
  27. out.println("<h1>Updated successfully!</h1>");  
  28. }  
  29. catch(Exception e)  
  30. {  
  31. System.out.println("e="+e.getMessage());  
  32. }  
  33. }  
  34. %>  
  35. <form name="f1">  
  36.   <table width="371" border="1">  
  37.     <tr>  
  38.       <th> Emp No </th>  
  39.       <td><input name="a" type="text" value="<%= num %>" onFocus="this.blur()">  
  40.       </td>  
  41.     </tr>  
  42.     <tr>  
  43.       <th>Emp Name </th>  
  44.       <td><input name="b" type="text" value="<%= name %>" ></td>  
  45.     </tr>  
  46.     <tr>  
  47.       <th>Salary </th>  
  48.       <td><input name="c" type="text" value="<%= sal %>"></td>  
  49.     </tr>  
  50.    <tr>  
  51.       <th colspan="2"><input type="submit"  name="s1" value="Save" >  
  52.       </th>  
  53.     </tr>  
  54.   </table>  
  55. </form>  
  56. </body>  
  57. </html>  
Now Run the application
 
Run the tomcat and start Mysql database then write the below line in the RL
 
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.
 
Output
 
update record using hibernate
 
To Delete Data
 
Follow the above process of "To Display Records" and made changes which I list below:
 
Creating a client of Hibernate

First five steps are the same as "Creating client of hibernate (to select or display)"
  1. Use executeUpdate() method of query to execute the HQL.
Now after compilation of Emp.java follow the process same as "To Update Data" till running the application.
 
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.
 
Output
 
delete record using hibernate
 
Thanks for reading