This content has been automatically translated from Ukrainian.
When we work with databases, we usually have to write SQL queries - samples, inserts, data updates, etc. But when the project grows, these requests become hundreds, and it becomes difficult to maintain them.
This is where it comes into play ORM (Object-Relational Mapping) - technology that allows you to work with a database through programming language objects.
ORM “translates the data from the tables in the database as objects that can be handled in code.
For example, instead of writing:
SELECT * FROM users WHERE id = 1;
at Ruby on Rails we just do:
user = User.find(1)
and we get a User object that has methods, properties and behavior like the regular Ruby class.
Benefits of ORM
- SQL minimum -most requests are generated automatically.
- Fewer mistakes - ORM checks types, relationships, validations.
- Faster development - CRUD operations (create, read, update, delete) are written in several lines.
- Portability - it's easy to change the DBMS (for example, from PostgreSQL to MySQL) without rewriting requests.
- Conveniently working with connections - has_many, belongs_to, has_one, etc.
Disadvantages of ORM
- Productivity - sometimes ORM generates “heavy” requests that need to be optimized manually.
- Black box - it's hard to understand what's going on under the hood.
- Not for everything - complex SQL queries or analytical samples 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 so as not to turn convenience into a performance trap.
This post doesn't have any additions from the author yet.