SD 1: What is an ORM?
Welcome to DailyDev.in!
At DailyDev.in, we make learning new software engineering concepts easy and fun, one week at a time.
Interested in diving deeper? Check out our latest post:
What’s Next for APIs? 4 Key Trends Shaping the Future
The API world is at a crossroads, poised for transformative change. From enabling seamless integrations to fueling the digital economy, APIs are the invisible engines driving modern innovation. But with emerging technologies like generative AI and edge computing
Table of Contents
Picture this: You’re on a treasure hunt. The treasure is a chest full of data (users, orders, inventory). But it’s locked inside a vault (database), and you don’t have the key. Now imagine you have a magical helper who knows the vault’s language and can retrieve or store your treasure with ease. That magical helper? It’s an ORM— Object Relational Mapper.
But don’t worry; we’re not diving straight into technical jargon. Let’s take it step by step, using stories, analogies, and a pinch of code magic to unravel the mystery.
The Great Divide: Code vs. Database
Your application and your database are like two neighbors who speak different languages. Your app speaks in objects (classes, methods, attributes), while your database talks in tables (rows, columns, SQL).
SQL stands for Structured Query Language and is a computer language that we use to interact with a relational database. It is mainly used for organizing, managing, and retrieving data from a computer database.
For example, in code, you might describe a person like this:
Python
class User:
def __init__(self, name, age):
self.name = name
self.age = age
But the database doesn’t understand this fancy “User” class. It expects something like this:
The ORM acts as the translator, ensuring both sides understand each other.
How Does ORM Work? Let’s Rent a Car
Imagine you’re at a car rental service:
You (the developer): You walk in and say, “I need a red sedan for 3 days.”
The Clerk (ORM): The clerk understands your request and translates it into a detailed system lookup: “Find all available cars where type = ‘sedan’, color = ‘red’, and mark them as reserved for 3 days.”
The Rental System (Database): The system fetches the appropriate car, processes your request, and reserves it for you.
Without the clerk, you’d need to learn the rental system’s complex interface, manually search for the car, and reserve it yourself. With the clerk (ORM), all the hard work is handled behind the scenes.
In database terms:
You writing code: “Fetch all users where the age is greater than 18.”
ORM translates: It generates SQL like
SELECT * FROM Users WHERE Age > 18;
.Database executes: The table rows matching your request are returned.
Let’s see this in action with C#:
Without ORM: Doing Everything Yourself
C#
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=myServer;Database=myDatabase;User Id=myUsername;Password=myPassword;";
string query = "SELECT * FROM Users WHERE Age > 18;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"Name: {reader["Name"]}, Age: {reader["Age"]}");
}
}
}
}
Here, you’re acting as the car rental clerk and the system, manually running SQL queries and processing the results.
With ORM: Renting Made Easy
C#
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
// Define the User class
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
// Define the DbContext
...
class Program
{
static void Main()
{
using (var context = new AppDbContext())
{
var adults = context.Users.Where(user => user.Age > 18).ToList();
foreach (var user in adults)
{
Console.WriteLine($"Name: {user.Name}, Age: {user.Age}");
}
}
}
}
In this ORM example:
You define a
User
class and anAppDbContext
to represent the database.ORM automatically translates the
.Where()
query into SQL and retrieves the results for you.
Why This Matters
Without ORM, you’d need to understand SQL deeply and manually handle queries, connections, and results. With ORM, you focus on writing code that describes what you want, and it handles how to get it.
This analogy shows how ORM bridges the gap between your application and the database, just like the rental clerk simplifies your car rental process.
Why Use an ORM?
Less Code, More Focus: Write meaningful code without worrying about SQL details.
Consistency: The ORM takes care of database connections, making your code cleaner and easier to debug.
Database Independence: Switching from SQLite to PostgreSQL? No problem—your ORM handles it.
Performance Considerations: Not All Magic is Instant
While ORMs are powerful, they’re not always the fastest solution. Think of them like a gourmet chef who takes slightly longer but guarantees a perfect meal every time.
When to Be Cautious
Extremely large datasets
Performance-critical applications
Scenarios requiring complex, optimized queries
The Philosophical Dimension
ORMs represent more than technical tools – they’re bridges between different programming paradigms. They embody the principle of abstraction, allowing developers to focus on solving business problems rather than wrestling with low-level data manipulation.
Choosing Your ORM Companion
Popular ORMs across languages:
Python: SQLAlchemy
Java: Hibernate
.NET: Entity Framework
Ruby: ActiveRecord
Bringing It All Together
An ORM is like your bridge to the database. It translates your code’s objects into something the database can store and understand, and vice versa. It’s not about avoiding SQL entirely but about empowering you to focus on the bigger picture while leaving the mundane tasks to your magical helper.
So the next time you’re working on an app and need to save or fetch data, remember you don’t have to do it alone. Let the ORM work its magic, while you focus on building the treasure map itself.
Now, go forth and code, treasure hunter!