Monday, October 1, 2012

What is the need of ORM framework like Hibernate ?

There are two models :
  • Object model
  • Relational model
Object model :
  • Object model is nothing but Object Oriented System.
  • In Object model system, objects are the components.
  • Objects are instances of classes.
  • Classes are related to other classes via inheritance relationships.
  • An Object model helps to create reusable application frameworks.
  • An Object has an identity, a state and behavior.
  • An Object model uses the principles of abstraction, encapsulation, polymorphism, modularity and typing.
Relational model :
  • A Relational model deals with Database.
  • Defines the structure of datadata manipulation, and data integrity.
  • Data is organized in the form of tables.
  • Different tables are associated by means of referential integrity ( a foreign key).
  • Integrity constraints such as primary key, unique check constraints, and not null are used to maintain an entity's integrity in the Relation model.

Mismatch or Difference between Object model and Relational model :
  • In an Object model, you use the state of the model to define equality between objects. But in aRelational model, you use primary key to define equality of entities.
  • Object references are used to associate different objects in an object model, whereas aforeign key is used to establish associations in a Relational model.
Because these two models are distinctly different, you need a way to persist object entities (Java objects) into a relational database.

Why do we need ORM (Object Relational Mapping) framework ?

Without ORM framework :
  • Need to interact with Database with direct SQL queries.
  • From an application developer point of view, it is very hard to write hundreds of lines of code in order to deal with Database for persisting data / fetching data or any DML operations to do.
  • In an Object Graph, let's say if there a number of objects associated with each other. So, as a developer after fetching data from multiple tables, we need to build result data into appropriate objects by iterating over ResultSet. It is a repetitive task every time dealing with database.  It is a headache to the developer.
With ORM framework :
    • In ORM framework, we think database tables as classes and each row as an object.
    • We don't interact with Database directly with straight forward SQL queries.
    • We think database interms of Classes and Objects only not tables and rows.
    • For example, If you want to save Employee object data. We instruct to ORM framework like hibernate to save Employee object by indicating some meta data about in which table data should be saved and which fields should be saved in which columns.

    Advantages of ORM framework :
    • Productivity : development time should be reduced.
    Disadvantages:
    • Performance : poor performance if huge amount of data exists. 

    Hibernate is one of the popular ORM framework.