Monday 7 October 2013

Introduction to Hibernate and ORM

Hibernate 1
  • Hibernate by defination it is an ORM(Object Relational Mapping) tool

  • ORM means which is used to map plain java objects to a tables Relational Database and vice versa



Lets we see in details of hibernate:
  • you have a java application which connects a relational database for example MySql
  • And I have a student class which contains members(variables) like name, Rollno, Address, Mobile which represents students information
  • Now you have created a Student object: like below
Student student=new Student(“Raj series”, 1, “India Hyderabad”, “98xxxxxx38”);
  • Now these information should store in the database which is there student object in to the student_info table.


  • If you are not using ORM framework like hibernate, you do this task using jdbc, and typically your code will look like this below:
public void insertStudentinfc(Student student)
{
Connection conn=null;
Statement stmt=null;
try
{
//step 1: Register JDBC DRIVER
class.forName(“con.mysqljdbc_Driver”);
//STEP 2: OPEN A CONNECTION
System.out.println(“connecting to a selecting database”);
conn.DriverManager.getConnection(“jdbc:mysql://localhost/STUDENTS”,”username”, “password”);
System.out.println(“connected database successfully”);

//step 3 write code to map java object student to the STUDENT_INFO table
System.out.println(“inserting records into the table”);
stmt=conn.createStatement();
String sql=”INSERT INTO STUDENT_INFO(Name,Roll_No,Address, Mobile)”+”VALUES(student.getName(),student.getRoll_No(),student.getAddress(),student.getMobile())”;
stmt.executeUpdate(sq)
System.out.println(“inserted student information into the STUDENT_INFO”);
}
catch(SQLException se)
{
//handling the jdbc errors
se.printStackTrace();
}
catch(Exception e)
{
//hadling errors for Class.forName()
e.printstackTrace();
}
finally
{
//STEP 4: finally block used to close resources
try
{
if(stmt!=null)
conn.close();
}
catch(SQLException se)
{
//do nothing
}
try
{
if(conn!=null)
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}//end finally try
}
}
}
// if you are using Hibernate, simple one statement is enough


Student student=new Student(“Raj series”, 1, “India Hyderabad”, “98xxxxxx38”);



  • We observe passing student object to the function insertStudentInfo() and manually mapping to the member variable to the columns of the table using sql query and here lies the major problem hibernate says as a java programmer : Why are you writing the SQL Queries in the java code(application)? Just leave that job to me, just pass the java object which you want to store or persist and implicitly I will generate and optimize SQL Query, and store the data into the data base table. So if you are using hibernate, the same code would like this:

public void insertStudentInfo(Student student)
{
Session session=Factory.openSession();
Transaction tx=null;
try{
tx=session.beginTransaction();
session.save(student);
tx.commit();
}
catch(HibernateException e)
{
if(tx!=null) tx.rollback())
e.printStackTrace();
}
finally
{
session.close();
}
}


  • just observe the above java code, there is no sql queries in your java application
  • Reduced the 80% of code compared to jdbc. It means that better code readability
  • Just pass the object to the save method and insert the record into the record
  • similarly if you want to retrieval the records in jdbc from the StudentInfo table in java application you first get the ResultSet and you frame a java object basically a collection object for example a list (ie: studentInfoList.add(student);)
Data Retrieval using JDBC:


ResultSet rs=stmt.executeQuery(“SELECT Name,Roll_No,Address,Mobile FROM Student_Info”);




//fetch each row from the result set
//and create a list object containing Student Info


List studentInfoList=new LinkedList();
while(rs.next())
{
String name=res.getString(“Name”);
String rollNo=res.getInt(“Roll_No”);
String address=res.getString(“Address”);
String mobile=res.getInt(“Mobile”);

//inserting records into the student object
Student student =new Student(name, rollNo, address, mobile);
studentInfoList.add(student);
}


  • For example a list (studentInfoList.add(student))result set , hibernate says
  • time: 2:38


No comments:

Post a Comment