Wednesday 24 December 2014

What is ORM?


ORM stands for Object-relational mapping. Hibernate maps your classes to relational tables automatically.

Let’s say I had an employee class like below, without ORM tool like hibernate, procedure to persist employee object looks like below.

public class Employee {
 private int id;
 private String firstName;
 private String lastName;
 private String designation;
 private int age;
 private double salary;
 
 public Employee(int id, String firstName, String lastName,
   String designation, int age, double salary) {
  super();
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
  this.designation = designation;
  this.age = age;
  this.salary = salary;
 }
 
 public int getId() {
  return id;
 }
 
 public void setId(int id) {
  this.id = id;
 }
 
 public String getFirstName() {
  return firstName;
 }
 
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 
 public String getLastName() {
  return lastName;
 }
 
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 
 public String getDesignation() {
  return designation;
 }
 
 public void setDesignation(String designation) {
  this.designation = designation;
 }
 
 public int getAge() {
  return age;
 }
 
 public void setAge(int age) {
  this.age = age;
 }
 
 public double getSalary() {
  return salary;
 }
 
 public void setSalary(double salary) {
  this.salary = salary;
 }
 
}


I had 4 employee objects like below.
Employee emp1 = new Employee(1, "Hari Krishna", "Gurram", "Senior Software Developer", 26, 80000);
Employee emp2 = new Employee(2, "Shreyas", "Desai", "Team Manager", 35, 150000);
Employee emp3 = new Employee(3, "Piyush", "Rai", "Senior Software Developer", 26, 100000);
Employee emp4 = new Employee(4, "Maruti", "Borker", "Software Developer", 26, 110000);


1.If you want to store above employee objects into database.

1.    You have to open connection to database.
2.   You have to create table like below.

CREATE TABLE employee
(
 id int,
 firstName varchar(30),
 lastName varchar(30),
 designation varchar(30),
 age int,
 salary decimal,
 PRIMARY KEY(id)
);
3. You have to insert employee details into employee table like below.
INSERT INTO employee values(1, "Hari Krishna", "Gurram", "Senior Software Developer", 26, 80000);
INSERT INTO employee values(2, "Shreyas", "Desai", "Team Manager", 35, 150000);
INSERT INTO employee values(3, "Piyush", "Rai", "Senior Software Developer", 26, 100000);
INSERT INTO employee values(4, "Maruti", "Borker", "Software Developer", 26, 60000);


Complete program to insert employee details to database looks like below.

/* Step 1: import sql packages */
import java.sql.*;

public class StoreEmployeeToDB {
 
  /* Update username, password and driver details here */
    static Connection getConnection(){
     try{
          /* Step 2: Load Driver */
         System.out.println("Loading/Registering driver");  
        
         Class.forName("com.mysql.jdbc.Driver");
          
         /* Step 3: Open connection to database */
         System.out.println("Connecting to database");
         String url = "jdbc:mysql://localhost/sample";
         String userName = "root";
         String pasword = "tiger";
         return DriverManager.getConnection(url, userName, pasword);   
     }
     catch(Exception e){
      e.printStackTrace();
      return null;
     }
    }
    
    public static void main(String args[]) throws SQLException{
     Connection conn = null;
     Statement stmt = null;
     
     try{
      conn = getConnection();

      /* Create table employee */
         String query = "CREATE TABLE employee(id int,firstName varchar(30),lastName varchar(30),designation varchar(30),age int,salary decimal,PRIMARY KEY(id));";
         stmt = conn.createStatement();
         stmt.execute(query);     
         
         /* Insert data to employee table */
         query = "INSERT INTO employee values(1, \"Hari Krishna\", \"Gurram\", \"Senior Software Developer\", 26, 80000)";
         stmt.execute(query);
         
         query = "INSERT INTO employee values(2, \"Shreyas\", \"Desai\", \"Team Manager\", 35, 150000)";
         stmt.execute(query);
           
         query = "INSERT INTO employee values(3, \"Piyush\", \"Rai\", \"Senior Software Developer\", 26, 100000)";
         stmt.execute(query);
 
         query = "INSERT INTO employee values(4, \"Maruti\", \"Borker\", \"Software Developer\", 26, 60000)";
         stmt.execute(query);
         
         query = "SELECT * FROM employee";
         ResultSet rs = stmt.executeQuery(query);
         
         while(rs.next()){
          int id = rs.getInt("id");
          String firstName = rs.getString("firstName");
          String lastName = rs.getString("lastName");
          String designation = rs.getString("designation");
          int age = rs.getInt("age");
          double salary = rs.getDouble("salary");
          System.out.println(id +"." + firstName + " " + lastName + " " + designation + " " + age + " " + salary);
         }
     }
     catch(Exception e){
      e.printStackTrace();
     }
     finally{
      if(stmt != null)
       stmt.close();
      if(conn != null)
       conn.close();
     }
        
    }
}


2. To retrieve employee records from database and map these to employee objects.

1.    You have to open connection to database.
2.   Execute the query "SELECT * FROM employee" statement
3.   Read record by record and map each record to one employee object.
4.   Close the connection.

Program looks like below.

/* Step 1: import sql packages */
import java.sql.*;
import java.util.*;

public class GetEmployeesFromDB {
  /* Update username, password and driver details here */
    static Connection getConnection(){
     try{
          /* Step 2: Load Driver */
         System.out.println("Loading/Registering driver");  
        
         Class.forName("com.mysql.jdbc.Driver");
          
         /* Step 3: Open connection to database */
         System.out.println("Connecting to database");
         String url = "jdbc:mysql://localhost/sample";
         String userName = "root";
         String pasword = "tiger";
         return DriverManager.getConnection(url, userName, pasword);   
     }
     catch(Exception e){
      e.printStackTrace();
      return null;
     }
    }
    
    public static void main(String args[]) throws SQLException{
     Connection conn = null;
     Statement stmt = null;
     List<Employee> empList = new ArrayList<Employee> ();
     
     try{
      conn = getConnection();
      if(conn != null){
       String query = "SELECT * FROM employee";
       stmt = conn.createStatement();
       ResultSet rs = stmt.executeQuery(query);
             
             while(rs.next()){
              int id = rs.getInt("id");
              String firstName = rs.getString("firstName");
              String lastName = rs.getString("lastName");
              String designation = rs.getString("designation");
              int age = rs.getInt("age");
              double salary = rs.getDouble("salary");
              Employee emp = new Employee(id, firstName, lastName, designation, age, salary);
              empList.add(emp);              
             }
      }
     }
     catch(Exception e){
      e.printStackTrace();
     }
     finally{
      if(stmt != null)
       stmt.close();
      if(conn != null)
       conn.close();
     }
     
     System.out.println("Employees in DB are");
     Iterator<Employee> iter = empList.iterator();
     while(iter.hasNext()){
      Employee emp = iter.next();
      System.out.print(emp.getId() + " ");
      System.out.print(emp.getFirstName() + " ");
      System.out.print(emp.getLastName() + " ");
      System.out.print(emp.getDesignation() + " ");
      System.out.print(emp.getAge() + " ");
      System.out.print(emp.getSalary() + "\n");
     }
    }
}


Now observe what we did above
1.   Opening connection to the database.
2.   Modeled table such that, Employee class can be mapped to employee table.
3.   Mapped each employee object to one record in employee table and save them in employee table.
4.   Retrieve each record from employee table and map each record to employee object.
5.   Close connection etc.

What Hibernate offers?
1.   Hibernate maps your class to table automatically.
2.   You no need to map data externally; Hibernate will do this for you.
3.   Hibernate works with all most all databases
4.   You just create class, Hibernate create database design for you. We will see it in later posts
5.   With the support of cache provided by hibernate; data is placed in cache for better performance.

You will understand benefits of Hibernate, once you are familiar with Hibernate.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment