.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

Display records using hibernate

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

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

Creating 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 session.
6.Create a reference of java.util.Iterator by using Iterate () method of query.
7.Fetch the object of POJO by using hasNext() method and next() method of iterator.

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

showEmp.jsp


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

<%@ 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">
<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>
</tr>
<%
}
session1.close();
%>
</table>
</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/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.


 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