What is an Object-Relational Mapping Framework?

orm
RCIX picture RCIX · Jul 20, 2009 · Viewed 89.7k times · Source

As the title says; what is a ORM framework and what is it useful for?

Answer

Lasse V. Karlsen picture Lasse V. Karlsen · Jul 20, 2009

A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.

In other words, instead of something like this:

String sql = "SELECT ... FROM persons WHERE id = 10"
DbCommand cmd = new DbCommand(connection, sql);
Result res = cmd.Execute();
String name = res[0]["FIRST_NAME"];

you do something like this:

Person p = repository.GetPerson(10);
String name = p.FirstName;

or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:

Person p = Person.Get(10);

Some also implement complex query systems, so you could do this:

Person p = Person.Get(Person.Properties.Id == 10);

The framework is what makes this code possible.

Now, benefits. First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to "get me all persons edited the last 24 hours" might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.

Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the "plumbing" necessary to talk to the database.