Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




ORM and Hibernate

ORM stands for Object Relational Mapping. Let us understand ORM with the below example :

Example :

You are a java programmer. You are given a task to get the Id and names of a few employees and save it to a table in database. So,

1. You would create a class named Employee,


class Employee{
    int id;
    String name;
    ---Getters & Setters---
}


2. Create an Employee object

Employee employee = new Employee();

3. Get the Employee id and name in Employee object.

employee.setId(1);
employee.setName("John");
Note : The id and name can be assigned from a web interface. I have used the setter method to keep things simple.


4. Now comes the steps to connect to database using java:

a. Register the Driver Class.
b. Create a Connection Object.
c. Create the statement object.
d. Execute the Query.
e. Close the Connection Object.

So using the above steps you can save the employee object to the database(using the Insert statement).

Now, if you have a close look at the table Employee:

Employee

id name
1 John

The Employee table above is exactly similar to the Employee class. So, don't you think we are doing a bunch of extra work in step 4.

What if there would be some software who could take care of the extra work. Luckily ORM provides a solution for the above scenario.

All we have to do is, assign the Employee object(i.e. Till step 3) as we do in java and the rest of the work(i.e. Tasks in step 4) will be taken care by the ORM. An ORM will not only insert the values but also create the table for you.

So, in an Object Relational Mapping, Object is the java object, Relational would be the relational database and Mapping is the connector which maps a java object with a table in a relational database.

Hibernate is one such ORM which we will be looking in detail.


Hibernate

Hibernate is an ORM used to map java objects to various relational databases. Hibernate has a configuration file where you can specify the details of which database to connect to and Hibernate will do the rest for you.

As a java developer, you create java objects and Hibernate internally converts them to SQL queries and inserts the values to the tables in a database.

Also it fetches data from database and converts them back to java objects, so that you being a java programmer can get the data in readable format.