ICTShore.com

We re-branded, ictshore.com is now accelerates.it!

What is ORM? Object-Relational Mapping Explained

What is ORM? A way to define your database with code

Share This Post

If you write Object-Oriented Code, having a place to store your data is a must. In fact, the traditional way to go is to use a Relational Database. You can use Microsoft SQL, MySQL, or PostgreSQL, but in any case, you know the pain. You have to spend time mapping between tables and your classes, create methods to save in the database and read from it, and so on. Well, not anymore my friend. In this post, we will explain what is ORM (Object-Relational Mapping), a solution that will solve all your pains.

If instead, you are searching for a free Relational Database, we can help you get started with MySQL. Here you find how to install MySQL on Windows and Linux, and here you have a great tutorial on MySQL queries.

What is ORM?

ORM stands for Object-Relational Mapping, it is a programming technique that abstracts your code from the database behind it. In plain English, if you are using ORM and a MySQL database, you could switch to PostgreSQL at any time without changing your code. At all.

What is ORM? Orm stands for Object-Relational mapping, and it is a way to define your database in the code
In ORM, your code defines your database.

Note: ORM goes together with Database Abstraction Layer (DBAL). As we will see, ORM lets you use classes instead of database tables, and those classes implement DBAL to save you from writing queries.

This is because, with ORM, you never write queries to the database in your code. Instead, you only interact with objects of specific classes, that represent records in the database. Obviously, at some point, someone needs to make actual queries to the database. But that’s not you, it is the ORM class that does it for you, in a way that is completely transparent.

ORM is also about not reinventing the wheel. You can find open-source ORM libraries for literally any programming language. Typically, such libraries provide you with something like a “database object” superclass, and you create other classes inheriting from that. You will use your classes to represent your data.

You don’t even need to create tables in your database. Depending on the ORM library, this is taken care of simply by looking at object definitions, or with migrations (more on that later).

An example of using ORM

Examples make everything clearer. Imagine you want to create an e-commerce website. Among many other things, you need to consider that a customer may have multiple shipping addresses to receive products. Thus, you need to take care of that in your data structure.

You start by modeling a new class, Account, to hold all the data of your customers like email, password, and so forth. Then, you create another class, ShippingAddress, to hold information about one individual address. When you do that with ORM, ORM creates two tables in the database (e.g. account and shipping_address) to map such objects.

Having the two objects is not enough. You need to define that the Account can have multiple ShippingAddress objects in it, so you simply define a property on it as an array of ShippingAddress. This is it, the code will take care of the relationship as well.

Now, depending on the programming language, you may do this in slightly different ways, but the core concept is always this one.

Database migrations

Unlike what you might expect, database migrations are not necessarily the transition from a database to another. Instead, they are the bread and butter of Object-Relational Mapping. Simply put a migration is an instruction to execute in the database to modify the database structure. A migration could create a new table, delete an existing one, or modify some fields or relationships.

You don’t write migrations using queries. Instead, you write them with the ORM syntax, and then ORM will create the queries for you in the proper way, depending on what database you are actually using.

Again, this varies from ORM library to ORM library, but the concept is always similar. You will have one file to define each migration, but each migration can contain multiple instructions. Furthermore, each migration must define two things: the up and the down. The up is what to do when implementing the migration, the down is what to do in case of rollback.

For example, a migration can create a table in its up part, and delete it in its down part. In this way, you can return back to the previous database configuration if needed.

Some ORMs go even further. They automatically build migrations for you by looking at the definition of your classes.

ORM Libraries

Now that we know what is ORM, we can get started with it. Below, some nice libraries to use ORM in various programming languages.

PHP

Eloquent (Laravel)

My favorite ORM in PHP is Eloquent, which comes packaged inside Laravel, a nice framework that helps you build nice applications. You can see Eloquent official documentation here. Below, an example of Eloquent code.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        /**
         * App\Phone is the class that represents the Phone object
         * That class also extends Model like this one
         */
        return $this->hasOne('App\Phone');
    }
}

And below, an example of migration.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateFlightsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('airline');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('flights');
    }
}

We took both examples from the official documentation linked above. Eloquent is a good choice, particularly if you are already using Laravel. More on Laravel? Check out our Laravel migration tutorial.

Other ORMs in PHP

Of course, Eloquent is not the only way to go for PHP. There are many ORMs out there, but this post is about what is ORM, so there is no point covering them all here. Yet, we can recommend two other ORMs:

As always, do your own research to find out which is the best ORM to fit your project.

Python ORM

Django

Django is a great python project that helps you to build a fully-fledged web application. Among its other features, it has an amazing ORM that can save you a lot of time. For example, with it, you don’t have to write migrations manually. Below, an example of its simplicity.

from django.db import models

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()

As you can see from the example, you directly define fields and relationships when defining the classes. In this case, the Album class references the Musician class (in the artist field). This example comes from the official Django documentation on models that you can find here.

SQLAlchemy

Another great ORM for Python that is worth considering is SQLAlchemy. Unlike Django models, this comes as standalone, which makes it a great alternative for standalone projects. You can read more about it from the official website.

Just one remark: it is probably easier to start with Django models than with SQLAlchemy, as Django gives you more automation.

C# ORM (Dapper)

If you are using C#, one of your best bets when it comes to ORM is Dapper. This NuGet library allows you to define objects instead of making queries. You can read more about it in the GitHub Dapper project. Like in the previous cases, an example below.

public class User
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string EmailAddress { get; set; }
    }

Java ORM (Hibernate)

If instead, you are a plain old Java Developer, you may want an ORM for that language. Java has been out there for a while, and you have many options, but probably the best way to go is Hibernate. Check out more in the official documentation.

Also there, you have to define classes and properties in them. Like any ORM, you will use that to represent your database structure.

Wrapping it up

In this post we saw what is ORM and, by extension, what is DBAL. In short, ORM is a programming technique where you write code, and that code gets translated into SQL queries for you. Many ORMs also implement Database Abstraction Layer (DBAL), meaning that they can translate code in many different database languages (MySQL, PostgresSQL, etc.).

With ORM, you are free from thinking about the database so that you can focus on your business logic. A great step up in productivity!

Picture of Alessandro Maggio

Alessandro Maggio

Project manager, critical-thinker, passionate about networking & coding. I believe that time is the most precious resource we have, and that technology can help us not to waste it. I founded ICTShore.com with the same principle: I share what I learn so that you get value from it faster than I did.
Picture of Alessandro Maggio

Alessandro Maggio

Project manager, critical-thinker, passionate about networking & coding. I believe that time is the most precious resource we have, and that technology can help us not to waste it. I founded ICTShore.com with the same principle: I share what I learn so that you get value from it faster than I did.

Alessandro Maggio

2020-05-28T16:30:23+00:00

Unspecified

Dev

Unspecified