Saturday, May 3, 2008

Active Records v/s Hibernate - Round II

Welcome to the round two of Active Record v/s Rails. This round is based upon implementation of ORM classes. Lets start with Hibernate. The steps to implement ORM class in Hibernate are:

  1. Name the class (preferable) according to the table. For example, if table is named Employee, then the class is also named Employee. This is preferable but optional.
  2. Next declare the instance variable corresponding to the attributes of the table with which class is to be mapped. For example, if the Employee table has an attribute named Name, then the class will have an instance variable named Name. Its data-type will be the Java equivalent of SQL type. If Name attribute is varchar, the name instance variable will be String.
  3. Last step is to implement getters and setters for the instance variables.

Next let us see how to do this with Active Record
  1. Name the class according to the table. For example, if table is named Employee, then the class is also named Employee. This is mandatory if you do not want to override the defaults.
  2. Derive the class from Base class of ActiveRecord package. For example, the Employee class needs to be derived from Base::ActiveRecord.
Thats it just two steps. No need to declare any instance variable or any getter/setter. So how does Rails gives you the data? It does it as follows:
  1. When the ORM object is created Rails reads the schema of the table and through meta-programming, creates corresponding instance variables in the ORM object.
  2. Next, Rails populates the object with the data from the table.
Using meta-programming and reflection Rails dynamically does everything. In the next post the third round will start on the basis of Query Language supported by both.

No comments: