Blog post featured image

What is an Object Relational Mapper (ORM)?

by 9D8

Published Thu Nov 02 2023

What is an ORM?

Have you been hearing about ORMs? What even are they?

Object-relational mapping (ORM) tools are a bridge between object-oriented programming languages and relational databases. An ORM allows developers to avoid SQL altogether and write queries in an approach that is native to their respective language.

What's even the point of an ORM? It allows developers to focus on application logic rather than the underlying database structure. ORMs map database tables to classes, table rows to objects, and table columns to object attributes. It makes working with relational data a dream!

When using an ORM, developers can define mappings between their classes and database tables. The ORM handles the translation between objects and database records behind the scenes. This simplifies database access by abstracting away the differences between object-oriented code and relational data.

How do ORMs Work?

As previously mentioned, ORMs work by translating the objects in an application to the data stored in a relational database. The ORM manages all the interactions with the database on behalf of the application.

The process starts when you define relationships between classes and the database tables. This is typically done by editing database schema. For example, there may be a User class that maps to a users table. The ORM uses these mappings to determine how to load data from the database into object instances.

Behind the scenes, the ORM converts method calls on objects into SQL queries. Calling user.save() may generate an INSERT or UPDATE statement to persist changes to the database. The ORM handles executing the queries and returning any results.

When fetching data from the database, the ORM will run SELECT queries and use the results to populate objects. This allows you to write simple object-oriented code without having to write actual SQL queries. ORMs can be extremely nice if you really don't like writing SQL. And honestly, you run into less problems when you can avoid writing SQL altogether for basic CRUD operations.

The Relationship Between ORMs and SQL

Don't hear us wrong, while ORMs handle the object-relational mapping process, SQL is still used under the hood. ORMs generate and execute SQL statements based on operations performed on objects. Having a solid understanding of how SQL works will help you as a backend developer probably almost more than anything else. For example, for simple CRUD operations, an ORM handles these conversions automatically. More complex queries, on the other hand, may still require you to use SQL directly. Most ORMs allow executing custom SQL while still taking advantage of the object-relational mappings.

Even if you're using an ORM, sometimes SQL gives you fine grain control over your data and queries that you wouldn't get otherwise. ORMs provides a higher level of abstraction making simple queries and operations easier, but it is not always a replacement for SQL - both have their place in application development. Remember, all things in development have intrinsic tradeoffs.

The Importance and Advantages of ORM

Object-relational mapping provide a lot of benefits that may increase your productivity and developer experience:

  • Productivity - ORMs simplify data access code substantially, allowing faster development. Basic CRUD operations are usually handled automatically.

  • Portability - ORM abstracts underlying database interactions, making it easier to switch database systems if needed. Only the ORM configuration needs to change. You could switch from Postgres to MySQL with greater ease.

  • Maintainability - ORM code tends to be more concise and consistent. The patterns used for data access are reused throughout the codebase.

  • Performance - ORM query optimization, caching, and batching can provide performance gains in many scenarios. My motto is "let the smart people build the SQL behind the ORM. I'll just use the ORM".

  • Code Safety - ORMs can automatically escape SQL parameters helping prevent SQL injection vulnerabilities. Type checking also helps catch errors early.

  • Reduced Boilerplate - ORMs eliminate most of the repetitive code needed to execute queries and map results to objects/classes.

  • Object-Oriented Design - ORM allows programs to interact with data using normal object-oriented approaches and patterns.

Even for small applications, I would seriously recommend using an ORM. It will save so much time and heartache. If you're building an app for production, just do yourself a favor and use an ORM. It's honestly the way to go.

The Challenges and Disadvantages of ORM

On the other hand, using an ORM isn't always sunshine and rainbows. It can come with disadvantages.

  • Performance Overhead - All the ORM object-relational mapping and abstraction adds some processing overhead. For simplistic systems, hand-tuned SQL may be faster. But, more often than not this is not the case.

  • Impedance Mismatch - Objects and relational data are fundamentally different. ORM tries to reconcile the differences which can sometimes result in awkward object modeling.

  • Steep Learning Curve - ORM frameworks require learning APIs and configuration techniques which can take time for you to pick up. But, I'd say it's worth it!

  • Leaky Abstraction - In advanced cases, you will still need knowledge of SQL and the underlying database to tune queries. The ORM abstraction can sometimes be leaky.

  • Vendor Lock-in - Relying heavily on an ORM makes it harder to switch if needed due to abstraction differences. Migrations between ORM systems can be challenging. Make sure the ORM you're using is very well maintained if it's open source. You wouldn't want it to stop working one day...

  • Limited Query Capabilities - Complex SQL queries are not always easy to handle through ORM, requiring you to drop down to SQL. This is pretty rare, but if you're doing something fancy then you'll probably need to go back to the core.

Is it worth it to use an ORM in web development?

The short answer is yes! The long answer is definitely!

ORM is an extremely useful tool for developing database-driven web applications. The advantages of higher productivity and maintainability directly translate to so many benefits for web projects.

How do I learn how to use an ORM?

If you're new to object-relational mapping, the best way to learn is to pick an ORM and start using it for sample projects. Getting hands-on experience is really the only way to learn.

When selecting an ORM, first consider your programming language and target database. For example, Eloquent for Laravel PHP with a MySQL database (if that's what you're into). Look for an ORM that is mature. What does this mean? Look for one that's been around a long time. If lot's of people have used it (and continue to), then it's probably good. Find one that is well-supported and integrated with your language/framework of choice.

Start small and simple! Use the ORM for basic CRUD operations, then advance to more complex queries and edge cases. Follow tutorials and documentation, but make sure you're spending quality time with the code.

Also don't skip straight to using an ORM if you don't know any SQL. Be sure to still understand the underlying SQL and database fundamentals. Learn how the ORM translates to SQL under the hood. When hitting limitations, don't be afraid to drop down to SQL for full control. There are many libraries that allow you to write SQL directly in your code, no matter the language.

If you're feeling lucky, even practive migrating schemas and switching databases to appreciate the abstraction benefits. Evaluate different ORMs on future projects to find one that best fits your programming style and data access patterns. This is how I came across Prisma. And, I love it!

Examples of ORMs to Help you in your Search...

  • Django ORM - This is the built-in ORM included with the Django web framework for Python.

  • Active Record - This is the ORM library included with Ruby on Rails.

  • Eloquent - This ORM lives in the PHP Laravel ecosystem

  • Prisma (our favorite) - An ORM for Typescript & Node.js

These are some of the more popular ORMs that we're familiar with. However, there are SO many more. Just do a quick Google search and you'll find a lot more.

Let's Summarize!

  • ORM provides object-relational mapping to translate between objects in code and relational data in databases.

  • ORM handles the dirty work of converting data, executing queries, and materializing results using metadata about class mappings.

  • Leading options like Eloquent, Django ORM, ActiveRecord, and Prisma are popular across languages and frameworks.

  • ORM boosts productivity and maintainability through its abstraction for common CRUD operations.

  • However, ORM does not eliminate the need to learn SQL and databases for complex queries or performance tuning.

  • The productivity and portability of ORM make it extremely useful for developing database-driven web applications.

  • Developers should learn ORM through hands-on experimentation with simple projects to appreciate the trade-offs.

That's it! Go give it a shot and let us know how it went. ORMs help speed us up at 9d8 and AlpineCodex. We can't imagine building production level code without them!

Side note: If you're wanting to learn how to use Prisma specifically, go check out our article on that along with the YouTube series on building a simple CRUD app with Prisma, SQLite, and NextJS App Router.