What is Object-Relational-Mapping (ORM)?
The purpose of an ORM library is to translate data between a relational database and objects in your application. In other words, it’s the middle layer that helps you interact with the database, using a language of our choice, instead of using SQL.
SQL query might look something like this:
SELECT * FROM users WHERE username = 'FunkyLadybug';
The same query would look something like this using an ORM library:
Why should I use an ORM?
- You get to use the language you already know, without having to master SQL.
- It abstracts away the database, so can switch from PostgreSQL to MySQL, without a problem.
- Some ORM libraries have very powerful features right out of the box.
My [very] limited experience using an ORM
As a junior web developer, my first exposure to an ORM was while learning Active Record as part of Ruby on Rails. Having some basic knowledge of SQL was helpful in grasping the fundamentals of Active Record, after reading over the documentation, I was set up and running in a few hours. This got me intrigued, what other ORMs are out there, and which one should I use for my next project.
- Sequelize: a promise-based Node.js ORM, which supports MariaDB, PostgreSQL, MySQL and SQLite. Sequelize has over 974,000 weekly downloads on npm and over 23k stars on Github.
- Objection: an ORM for Node.js that provides an easy declarative way to define models and relationships and a simple way to write queries using the full power of SQL. Objection has over 98,000 weekly downloads on npm and over 5.5k stars on Github.
This is just a shortlist of the most common ones I uncovered in my research, however, there are many many more to choose from. It can be very overwhelming, especially for beginners like myself. To choose, ask yourself these questions:
- Which database am I using? Is it supported in the ORM I am exploring?
- Is there clear documentation for this ORM?
- What are the supported features?
- Performance of the ORM
I prefer SQL, are there any reasons not to use ORMs?
Interestingly enough, not everyone is a fan… I came across a few articles debating that ORMs should not be used. Key objections include:
- There are dozens of ORMs for Node.js (and hundreds for all platforms). Learning one will not easily translate to another, and so having to learn multiple tools can become overwhelming. However, there is only one SQL dialect to worry about, and so it’s easier to transfer knowledge between platforms.
- Some complex ORM calls can be inefficient and slow.
- An ORM can’t handle all queries, and ultimately you will need to go back to using SQL.
This is a summary from a junior web developer point of view, and the main things that came to mind after first learning SQL, and then being exposed to an ORM. There is no clear answer as to whether or not you should use an ORM, and if yes, which one. It’s about understanding your needs and what is the best fit for your application.