AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1069&pId=-1
Introducing Object Relational Mapper
page
by Uday Denduluri
Feedback
Average Rating: 
Views (Total / Last 10 Days): 39537/ 67

Introduction

Object-Relational mapping (O/RM, ORM, and O/R mapping) is a programming technique that links databases to object-oriented language concepts, creating (in effect) a "virtual object database." The package that implements the Object relational Mapping is known as Object Relational Mapper or ORM.  ORM can be used in an n-tier application.  There are many ORM packages available in the market both for free and commercial usage.  However, some programmers develop their own ORM packages for the same.

Conventional Programming Model without ORM

Let us understand the conventional programming model before we go into actual implementation of the ORM.

Figure 1

We have a presentation layer that deals with User Interfaces and we have a Business Logic layer which deals with the business rules of the application.  In 3-tier applications we have a dedicated layer that deals with the database related activities called as Data Access layer (DAL).  DAL typically deals with connecting to database executing the commands or stored procedures and getting the resultant sets.

Disadvantages of the Conventional Model

Let us go over the differences of the above conventional model.  Here disadvantages are given in the sense to understand the advantages of the ORM

• The stored procedures or SQL commands need to be written well in advance.

• Does not support multiple databases – The stored procedures written are only for the SQL server.  The same has to be done for other databases as well.

• Writing SQL queries is a laborious task as well as error prone.

• Most developers do not like writing SQL queries as they do not want to get out of Object oriented world.

• Queries involving even the smallest business logic need to be changed in case of change in the business rules.

What is ORM?

Let us understand the ORM with a help of a figure given below.

As we can see from the figure above that there is a new layer that gets introduced called ORM. This layer acts as a bridge between DAL and database.  It generates SQL queries maps the Objects to the Tables.

ORM – Object Relational Mapper is a package that maps the objects to the relational tables and Tables columns to the object attribute one to one.

Example:  We have an Employee Table with some columns in it.  The figure below shows a business object of type Employee.  It is not mandatory to have the employee declaration as shown below.

The Code written below is in C#.  It typically explains a skeleton of business object.

Listing 1

Class Employee
{
  public ID;
  public Employee Name;
  public Employee Salary;
}

The Employee class created needs to have a metadata that helps the ORM map to the table. There are many ORM packages available that deal with encapsulating the metadata with the class.  We will look at the same in the next section.

Figure 2

Advantages

Advantages of the ORM are illustrated below.

·         Automatic generation of SQL statements – The ORM layer generates automatically SQL statements.  This helps the programmers concentrate more on the actual business logic removing the overhead of the SQL statements.

·         Support of the Multiple Databases – Majority of the ORM packages available in the market support ANSI SQL standards.  Hence, they can be used with most of the RDBMS.  This can very useful in product development.

·         ORM emphasizes on fully following the object oriented approach.  Every thing is an object. Database CRUD operations are typically called as a function.  We will have functions on the business objects like Save, Update and Delete.

Disadvantages

Even ORM has its own limitations.  Let us understand them.

·         Lack of standards – We have variety of ORM packages available in the market.  We do not have common standard or conventions followed.  Lack of such standard has made the programmers job tough.  An ORM package may be completely different from another one.

·         Performance related issues - Most of ORM related packages use reflection.  As we know, using   Reflection excessively is a performance overhead.  (But there are some ORM packages which do not use the same.)

Comparing ORM and Conventional Model

Let us compare the ORM with Conventional model to have a better understanding of the ORM.

Conventional Model

ORM Model

Programmer needs to write all the SQL queries for each and every interaction with the database.

Programmer needs not write even a single SQL query for any interaction with the database.

It is tough to handle the changes to the SQL queries in case of any change requests.  This is in comparison with ORM.

The change requests to any database related activities can be done in a very easy way.  As these are classes and methods we can keep the track of the changes with version control systems pretty accurately.

We generally have a separate team for handling DDL (Data Definition Language) and DML (Data Manipulation Language) issues.

We may have a team for the same here, but their work will be limited to only DDL. As we do not have DML in form of queries, programmers are responsible for the DML related tasks.  Hence, programmer has a better control on the same.

Support for Transactions is available.

It is a common notion that Transactions are not available in ORM. But Support for the Transactions are very much available.

Chance of Errors due to the SQL queries. This is more as the complexity of the SQL queries.

Chance of Errors is less as we have our code written in classes and methods.

We have some Interfaces to the database to see the execution of the SQL statements like Query Analyzer.  This helps the programmer for testing the database.

In most of the ORM packages we do not have such a kind of facility.  Some of the ORM packages have their own language called as OQL – Object query Language.

Case study – Gentle.NET: An ORM Tool

Gentle.NET is a free ORM framework.  In this section let us understand in how to use the same by creating a custom business objects.

Overview

Gentle.NET is an RDBMS independent object persistence framework. It features automatic SQL generation and object construction, an SQL factory for creating custom queries, Data View construction helpers and excellent performance and reasonably complete docs.  The gentle framework defines few attributes that help the Business Objects relate with the tables in the database.

Business objects may optionally inherit from the Persistent class, which provides a set of standard methods for persisting and retrieving objects.  We can replicate these on a different base class if needed or on a manager class if you prefer a more SOA-oriented design.  Gentle provides support for identity columns (where the database assigns a primary key value to the row being inserted) to implementers of IPersistent (which includes the Persistent class).

Business Objects

Let us take a simple Business object called “Employee.” It has only two attributes called as “employeeID” and “employeeName.”  We have a table Employee which has two columns “employeeId” and “employeeName” where “employeeId” is a primary key.  The Code written below is in C# and shows a simple business object.  These changes to the code need to be observed with regards to the Gentle .Net.

Listing 2

public class Employee
{
    private int employeeId;
    private string employeeName;
 
    // Constructor of the Employee class.
    public Employee( int employeeId, string employeeName )
    {
        this.employeeId = employeeId;
        this.employeeName = employeeName;
    }
 
    public int Id
    {
        get{ return employeeId; }
        set{ employeeId = value; }
    }
 
    public string Name
    {
        get{ return employeeName; }
        set{ employeeName = value; }
    }
}

Let us look at the changes need to be done to the “Employee” class.  We add the Meta data information to the employee class so that Gentle.NET understands that Employee class corresponds to the Employee table in the database.  We also need to map the column names on One-One basis.  The Code written below is in C# and shows the internals of the Gentle.NET.  We need to have Gentle Framework to run the same.

Listing 3

[TableName("Employee")]
public class Employee
{
    private int EmployeeId;
    private string EmployeeName;
 
    public Employee( int EmployeeId, string EmployeeName )
    {
        this.EmployeeId = EmployeeId;
        this.EmployeeName = EmployeeName;
    }
 
    [TableColumn("EmployeeId"), PrimaryKey]
    public int Id
    {
        get{ return EmployeeId; }
        set{ EmployeeId = value; }
    }
 
    [TableColumn(NotNull=true)]
    public string Name
    {
        get{ return EmployeeName; }
        set{ EmployeeName = value; }
    }
}

We have the following observations from the Listing 3.

·         An Attribute by the name “[TableName ()]” – This attribute helps the Gentle framework make a relationship between the business object and Table name. The name given in the attribute should match with the name of the Table in the database.

·         An Attribute by the name “[TableColumn()]” – This attribute helps the Gentle Framework identify the map the column name and the property in the class.  Apart from identifying the column names we can also give more information like “Primary key” and “Not Null.”

Interaction with the Database – Using Broker class

Let us now understand the interaction with the database with the same business object employee.  

Listing 4

Employee employee = new Employee (42, "FirstName LastName");
Broker.Insert( employee ); 
// save the Employee to the database
Key key = new Key typeof(Employee), true, "Id", 42 ); 
// create a key //with a single selection criteria value
employee = Broker.RetrieveInstance( typeof(Employee), key ) as Employee; 
// load the specified Employee from the database

We have the following observations from the Listing 4.

·         A class by name Broker acts like an interface that inserts the new object employee.  Broker class has method called as “Insert” which takes the employee object.

·         A class by the name Key is used in the gentle framework that helps to create a Key.  This key is useful to retrieve the employee object.

·         Broker class has another method called as RetriveInstance.  This method takes 2 parameters: type information of business object and Key information.

Interaction with the Database – Without Broker class

We can avoid using the Broker class for interacting with the database.  Gentle Framework has an interface called as IPersistent.  Gentle has a class Persistent that implements the interface IPersistent.  Business classes can inherit from Persistent class.

Listing 5

using Gentle.Framework;
 
[TableName("Employee")]
public class Employee : Persistent
{
    private int EmployeeId;
    private string EmployeeName;
 
    // this is used by clients to construct new Employees
    public Employee( string EmployeeName ) : this( 0, EmployeeName ) {}
 
    // this is used by Gentle to reconstruct objects read from the //database
    public Employee( int EmployeeId, string EmployeeName )
    {
        this.EmployeeId = EmployeeId;
        this.EmployeeName = EmployeeName;
    }
 
    // this is used by client to fetch Employees from the database
    static public Employee Retrieve( int EmployeeId )
    {
        Key key = new Key( typeof(Employee), true"Id", EmployeeId );
        return Broker.RetrieveInstance( typeof(Employee), key ) as Employee;
    }
 
    [TableColumn("EmployeeId"), PrimaryKey(AutoGenerated=true)]
    public int Id
    {
        get{ return EmployeeId; }
        set{ EmployeeId = value; }
    }
 
    [TableColumn(NotNull=true)]
    public string Name
    {
        get{ return EmployeeName; }
        set{ EmployeeName = value; }
    }
}

We have the following observations from Listing 5.

Employee class is inherited from the Persistent class.  The Persistent class has a method “Retrieve” which returns the type Employee.  It internally uses Broker class.

Interaction with the Database using Transactions

We can handle Transactions with the Gentle framework.  We have a class by the name Transaction.  Let us understand the usage of Transactions with the help of a code snippet.  The Code written below is in C#.  The code below explains the usage of the Transaction class in the Gentle Framework.

Listing 6

try
{
    Employee employee = new Employee();
    Transaction transaction = new Transaction();
    transaction.Persist( employee );
    transaction.Commit();
}
catch( Exception e )
{
    // rollback transaction and release database connection
    transaction.Rollback(); 
    // rethrow the exception
    throw; 
}

We have the following observations from Listing 6.

·         Transaction is a class in Gentle Framework which can be used for the handling transactions with the usage of the Gentle framework.

·         Transaction has a method by the name Persist.  This method stores the values of the object passed in the parameter.

·         Transaction has a method called as commit which commits all the data base operations.

·         Transactions can be rolled back.  The method Rollback helps to achieve the same.

References
Conclusion

Object Relational Mapper (ORM) is the layer between application and database which automates the SQL query generation.  In applications with ORM everything is an object.  Application interacts with the database as it is it is interacting with another object.  Hence, erroneous tasks like writing SQL queries can be avoided.  The same valuable time can be spent in much better tasks.

ORM also has its own limitations.  The need of the hour is to have a common standard that need be adopted by the all the ORM packages.  The performance related issues also need to be taken care of.  Until or unless both of these happen we cannot see the ORM implemented applications prosper.

There are varieties of ORM packages available in the market, but choosing one of them would be a wise decision.  The features of the package should be thoroughly investigated.  Based upon the same a decision has to be taken.  We have both commercial as well as free packages available.


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 3:01:50 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search