Saturday 27 February 2016

ORM (Object Relational Mapping) is Not a Magic at ALL

How ORM works in background?
From the name itself, it says that

  • Map the object with relational database and keep the meta data(mapping informations). e.g. class against table name, fields of the class against columns of the table
  • Generate SQL on demand in background using the meta data and Java Reflection API. e.g. for saving an object it generates INSERT query corresponding to the table and fields for which the object is mapped. Similarly to find, update and delete, it generates SELECT, UPDATE and DELETE queryies respectively.

Here I have demonstrated how Hibernate(one of the ORM implementations) works internally using Java core API(including Reflection API) and JDBC API (not Hibernate API). Download/Fork project  from https://github.com/PrabhatKJena/HibernatePOC

First of all let's see how the code looks like when we are working with ORM.
Test.java
Output:
Here you can observe the code looks like Hibernate code but there is no hibernate API used. 

Now let's have a look into the code in background.
This is the config file (like hibernate-configuration) where JDBC connection details are configured. 

These are our custom annotations similar to @Entity@Column in Hibernate.

This is the Configuration class which is responsible for loading JDBC driver and set JDBC properties to SessionFactory (nothing but a JDBC Connection Factory)

This class is like a JDBC Connection factory which creates and returns JDBC Connection as a Session object.

This is the important class (same as Session in Hibernate) which provides methods to persist, update, get and delete an entity.

 This is a helper class which contains the meta data (mapping informations) about the entity class.


This is the most important helper class which is responssible for the antire secret behind ORM. 
  • Introspects the enity class and stores the meta data(mapping infromations) 
  • Generates the SQL on demand for every operations like insert, update, find, delete using Java Reflection API
The entire framework works with Reflection and Annotation API.




Thank You for Visiting the blog. Please feel free to share yout comment/suggestion. 





No comments:

Post a Comment