Why we need ORM

Isuru Jayalath
Nerd For Tech
Published in
5 min readMar 3, 2024

What are ORMs

So what is an ORM? It stands for Object-Relational Mapping. It’s a programming technique used in software development to bridge the gap between the object-oriented programming paradigm and relational databases.

In traditional relational database systems, data is stored in tables consisting of rows and columns. These tables have relationships defined by keys (primary and foreign keys). However, when we work with object-oriented programming languages like Java, Python, or C#, data is typically represented as objects with attributes and methods.
ORM frameworks provide a way to map these object-oriented concepts to relational database structures.

Simple terms

In simple terms, ORM acts as a bridge between your application code (written in an object-oriented language like Python, Java, etc.) and your database (which typically stores data in tables, rows, and columns). Instead of writing SQL queries directly, you work with objects in your code, and the ORM translates these objects into database operations.

For example, if you have a Python class representing a “User” in your application, the ORM can handle tasks like saving a new user to the database, retrieving existing users, updating user information, and deleting users. All these operations are done through the ORM’s methods, without you needing to write raw SQL queries. Essentially, ORM simplifies database interaction by allowing you to work with your database using the programming language’s native objects and methods rather than dealing directly with SQL.

Advantages of ORMs

  1. Increased Productivity:
    ORM frameworks abstract away the complexities of database interactions, allowing developers to work with objects and classes instead of writing raw SQL queries.
  2. Object-Oriented Paradigm:
    ORMs align database operations with the object-oriented programming paradigm, making it easier for developers to model and manipulate data using familiar concepts such as classes, objects, and inheritance. This alignment enhances code readability, maintainability, and reusability.
  3. Automatic Schema Generation:
    Many ORM frameworks offer features for the automatic generation of database schemas based on object mappings. This eliminates the need for manual schema creation and synchronization, streamlining the database deployment process and reducing human error.
  4. Cross-Platform Compatibility:
    ORM frameworks are often compatible with multiple programming languages and platforms. Developers can use the same ORM library across different projects or platforms, enhancing code consistency and reducing learning curves.

Popular ORMS

ORMs are available for various backend frameworks and programming languages.

  1. Sequelize: (Node.js)

A promise-based ORM for Node.js that supports multiple database systems, including MySQL, PostgreSQL, SQLite, and MSSQL. Sequelize provides a wide range of features, such as model definition, associations, validation, and transactions.

2. Hibernate: (Spring Boot)

One of the most popular ORM frameworks for Java, Hibernate, is often used with Spring Boot applications. It simplifies database interactions by mapping Java objects to database tables and providing features like lazy loading, caching, and automatic schema generation.

3. Entity Framework Core: (.NET)

Microsoft’s official ORM framework for.NET Core and ASP.NET Core applications. Entity Framework Core enables developers to work with databases using LINQ queries and offers features such as automatic migrations, code-first development, and database seeding.

4. Django ORM: (Django)

Built-in ORM provided by the Django web framework for Python. It offers an intuitive way to interact with databases using Python objects and provides features such as querysets, model relationships, and migrations.

Now, let’s see how we can use sequelize with a Node.js backend and MySQL database.

First, create a Node.js backend. Your folder structure should look like this.

Before getting started, you should install several dependencies. You can follow this command for that.

npm i express fs mysql2 path sequelize sequelize-cli

The config.json file specifies the database connection details for different environments, such as development, test, and production. For this example, give your database credentials under development.

{
"development": {
"username": "root",
"password": "1234",
"database": "test",
"host": "localhost",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}

Inside the models, you can create tables in your database. First, create the Customer table as a model.

module.exports = (sequelize, DataTypes) => {
const Customer = sequelize.define("Customer", {
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true
},
address: {
type: DataTypes.STRING,
allowNull: false,
},
phone: {
type: DataTypes.STRING,
allowNull: false,
}

});

Customer.associate = models => {
Customer.hasMany(models.Order, {
foreignKey: 'customerEmail', // Assuming customerEmail is the foreign key in the Order table referencing Customer's email
as: 'orders' // This will allow you to access a customer's orders using `customer.orders`
});
};

return Customer;
};

Then, Let’s create the Order table

module.exports = (sequelize, DataTypes) => {
const Order = sequelize.define("Order", {
orderId: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true,
},
totalAmount: {
type: DataTypes.FLOAT,
allowNull: false,
},
});

Order.associate = (models) => {
Order.belongsTo(models.Customer, {
foreignKey: "customerEmail", // Assuming customerEmail is the foreign key in the Order table referencing Customer's email
targetKey: "email", // The target key in the Customer table to which the foreign key in the Order table refers
});
};

return Order;
};

In the customer table, email is the primary key. In the Order table, orderId is the primary key. There is a one to many relationship between Customer and order (the Customer has many orders). The index.js file will be added automatically when you are installing “sequelize” and “sequelize-cli.”.

Your main index.js file should look like this:

const express = require("express");
const db = require("./models");
const app = express();
app.use(express.json());

db.sequelize.sync({ force: true }).then(() => {
app.listen(3001, () => {
console.log("Server running on port 3001");

db.Customer.create({
name: "John Doe",
email: "john@example.com",
address: "123 Main St",
phone: "555-1234",
})
.then((customer) => {
console.log("Customer created:", customer);
})
.catch((error) => {
console.error("Error creating customer:", error);
});

db.Order.create({
orderId: "123456789",
totalAmount: 100.0,
customerEmail: "john@example.com",
})
.then((order) => {
console.log("Order created:", order);
})
.catch((error) => {
console.error("Error creating order:", error);
});
});
});

Here first, we have to set up an Express backend server, and after that, synchronize the sequelize models with the database using the sequelize.sync() method, and then start the server on port 3001.

Then let’s see how we can add data to the Customer and Order tables. Without ORMs, you have to write queries like INSERT INTO Customer values(“John Doe”,…). But with the aid of ORMs, it’s not that hard. You just need to pass the respective values to the create method of the relevant model, as in the above example.

In conclusion, Object-Relational Mapping (ORM) is a powerful technique that simplifies database interactions in software development by bridging the gap between object-oriented programming languages and relational databases. In this blog, we explored how to use Sequelize, a popular ORM for Node.js, with a MySQL database. Through a step-by-step guide, we learned how to set up a Node.js backend, define models for database tables, establish associations between models, and perform operations using Sequelize methods.

--

--

Isuru Jayalath
Nerd For Tech

Undergraduate of University of Moratuwa, Faculty of Information Technology.