This content has been automatically translated from Ukrainian.
When we work with databases, we usually have to write SQL queries - selections, inserts, updates, etc. But as the project grows, these queries can number in the hundreds, and maintaining them becomes difficult.
This is where ORM (Object-Relational Mapping) comes into play - a technology that allows you to work with the database through objects of the programming language.
ORM “translates” data from tables in the database into objects that can be worked with in code.
For example, instead of writing:
SELECT * FROM users WHERE id = 1;
in Ruby on Rails we simply do:
user = User.find(1)
and get a User object that has methods, properties, and behavior like a regular Ruby class.
Advantages of ORM
- Minimum SQL - most queries are generated automatically.
- Fewer errors - ORM checks types, relationships, validations.
- Faster development - CRUD operations (create, read, update, delete) are written in a few lines.
- Portability - easy to change the DBMS (for example, from PostgreSQL to MySQL) without rewriting queries.
- Convenient handling of relationships - has_many, belongs_to, has_one, etc.
Disadvantages of ORM
- Performance - sometimes ORM generates “heavy” queries that need to be optimized manually.
- Black box - difficult to understand what happens under the hood.
- Not for everything - complex SQL queries or analytical selections are better written manually.
Examples of ORM
- Ruby - ActiveRecord
- Python - SQLAlchemy, Django ORM
- JavaScript - Sequelize, Prisma
- PHP - Eloquent (Laravel)
In short. ORM is a bridge between the world of objects and tables. It allows developers to think less about SQL and more about business logic. But like any tool, ORM is worth understanding to avoid turning convenience into a performance trap.
This post doesn't have any additions from the author yet.