In simple terms, ORMs (Object-Relational Mappers) are tools for interacting with databases using OOP (Object-Oriented Programming). Instead of writing raw SQL queries, you can use objects to perform database operations.
This abstraction makes database work easier, especially for developers unfamiliar with SQL (though I’d argue SQL knowledge should be fundamental).
INFO
You can also find ODMs (Object-Document Mappers) for NoSQL databases, which work similarly but are designed for document-based databases like MongoDB.
Pros and cons
Like anything in software development, ORMs come with their own set of advantages and disadvantages.
Some pros of using ORMs:
- Faster development time, less boilerplate code
- Easier to read and maintain code
- Database abstraction for easier switching between DBMS
- Built-in security features against SQL injection
- Additional features like migrations and validations
Some cons of using ORMs:
- Performance overhead compared to raw SQL
- Limited control over generated SQL queries
- Not always suitable for complex queries or large-scale applications
- Can lead to misuse or over-reliance on the ORM, resulting in inefficient database interactions
Use ORMs when rapid development and maintainability are priorities; use raw SQL for performance-critical or complex-query scenarios.
How ORMs work
ORMs map database tables to classes and rows to objects. For example, a User table in a database can be represented as a User class in your code. You can then create, read, update, and delete records using methods on the class.
Example with Drizzle ORM
The following example demonstrates how to use Drizzle ORM with a SQLite database in a TypeScript environment.
import { drizzle } from 'drizzle-orm/better-sqlite3';
import { text, sqliteTable } from 'drizzle-orm/sqlite-core';
import Database from 'better-sqlite3';
const users = sqliteTable('users', {
name: text(),
email: text(),
});
const db = drizzle(new Database(':memory:'));
db.insert(users).values({ name: 'Alice', email: 'alice@example.com' });NOTE
Noticed how we defined a
userstable and inserted a new user without writing any SQL queries.
Conclusion
It’s worth mentioning that one of the most important things for any application is the data structure and how data is modeled. ORMs can help with that, but they are not a silver bullet.
Every developer should understand how to interact with databases using raw SQL, especially how to write efficient queries. ORMs can be a great tool, but they should not be a crutch.