Hibernate for beginners

I was going through basics of Hibernate and thought of sharing this with all.

What's Hibernate?

Hibernate is a Java framework that simplifies the development of Java application to interact with the database. Basically it is an open source, lightweight, ORM (Object Relational Mapping) tool. It implements the specifications of JPA (Java Persistence API) for data persistence.

Why ORM?

An ORM tool simplifies the data creation, data manipulation and data access. It is a programming technique that maps the object to the data stored in the database.

orm.jpeg

Consider you have a java program which has a class defined in it and we have created objects of that class.

public class Student {
   private int id;
   private String firstName; 
   private String lastName;   
   private String course;  

   public Student() {}
   public Student(String fname, String lname, String course) {
      this.first_name = fname;
      this.last_name = lname;
      this.course = course;
   }

   public int getId() {
      return id;
   }

   public String getFirstName() {
      return first_name;
   }

   public String getLastName() {
      return last_name;
   }

   public int getCourse() {
      return course;
   }
}

Consider the above objects are to be stored and retrieved into the following RDBMS table −

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   course     VARCHAR(20)  default NULL,
   PRIMARY KEY (id)
);

Now, how do we store these objects into database?

  1. RDBMSs do not define anything similar to Inheritance, which is a natural paradigm in object-oriented programming languages.

  2. Object-oriented languages represent associations using object references whereas an RDBMS represents an association as a foreign key column.

The Object-Relational Mapping (ORM) is the solution to handle all the above impedance mismatches and Hibernate is one of them.

Advantages of Hibernate Framework

1) Open Source and Lightweight

2) Fast Performance The performance of hibernate framework is fast because cache is internally used in hibernate framework. There are two types of cache in hibernate framework first level cache and second level cache. First level cache is enabled by default.

3) Database Independent Query HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the database independent queries. So you don't need to write database specific queries. Before Hibernate, if database is changed for the project, we need to change the SQL query as well that leads to the maintenance problem.