This blog is subject the DISCLAIMER below.

Tuesday, November 20, 2007

Object Relational Mapping (ORM)

Object relational mapping or ORM, is the concept of reflecting the state of business objects to be stored in a database, the concept itself is already known, the difference is in how we can do it?.
In normal cases; a developer will connect to a database then write SQL queries to be executed against it, so , it is not a problem, isn't it??.

The main problem in the previous scenario is that a business logic developer must know SQL, and must embed SQL code in the database layer in the application. Another thing is if the schema changes, it would be a tedious task to rewrite SQL queries to fit with the new schema. Last but not least; sometimes DBMS systems have slight difference in their SQL syntax and data types, So, if for any reason an application migrates from using a certain DBMS to another, some problems might show up. Well, what is the solution then??
The solution is simply founding an intermediate layer between an application and a database, this layer encapsulates any thing relating to storing, deleting, updating and retrieving objects, a layer responsible for defining associations between business objects like; composition and inheritance to be expressed in the relational model in the form of database tables.

There are many ORM tools like; Toplink and Hibernate, however, hibernate is the most famous these days. When working with an ORM framework; the developer is responsible for defining the how a certain object will be mapped to the database; in other words; telling the framework how a certain business object will be saved in the database. The next code fragment shows a simple java code for defining an object named category.

public class Category {
private int id;
private String name;
private String description;
}


The previous object can be defined for mapping like this in a XML file as follows using Hibernate




That's it, when you are accessing the database in your application, you just make calls to save, delete,update and load methods , so if the schema needs altering, all what is needed is to modify the XML file and telling the framework to regenerate the schema without any modifications the actual business logic and without writing a single SQL query. The category object is simple,however, any kind of complex associations can be mapped using the same way.

The best thing in ORM is that it frees a designer's mind from going beyond business relations, as there is no need to think of how to express them in the relational model any more. When you start using ORM frameworks, things will be upside down for a while, then, it will really make sense.

2 comments:

m-hewedy said...

Good introduction about ORM.
go on if your time permit.

Mohamed Abd El hafeez said...

good article but can you explain what is the meaning of buisness layer ???