An ORM (object-relational mapper) lets your code work with database data as ordinary objects, and writes the SQL for you. It saves you hand-writing the same queries over and over. The SQL still runs, though, and knowing what it looks like is how you avoid the slow cases.
Two worlds that don't match
A relational database stores data in tables: rows and columns, linked by keys, and you talk to it in SQL. Your application code thinks in objects: a User with a name and a list of orders. Getting from one to the other by hand means, for every feature:
- Writing a SQL string.
- Sending it to the database with the right values.
- Turning each row that comes back into an object, column by column.
Do that for every read and write in an app and you end up with hundreds of near-identical queries. Joins get copied and tweaked, a renamed column breaks queries you forgot about, and a typo in a SQL string only shows up when that line runs. The gap between the two models has a name: the object-relational impedance mismatch.
An ORM closes most of that gap. You describe your data once, as classes, and the ORM handles the SQL and the conversion in both directions.
How the mapping works
Every ORM works from the same three rules:
| In your code | In the database | Example |
|---|---|---|
| A class | A table |
Wondering how this was made? How we make these