DEV Community

Jonathan Hall
Jonathan Hall

Posted on • Originally published at jhall.io on

You're ORMing wrong

Object-Relational Mapping (ORM) is pretty ubiquitous these days. Many people take for granted that you’ll be using an ORM in your app. The question is usually “Which ORM should we use?” not “Should we use an ORM?”

This mindset leads to many misuses and abuses of ORMs. Today I’ll talk about one of them.

Imagine you’re selling widgets in a web store. You store the widget data in a table in your relational database.

When it comes time to display the widgets to your web site vistor, you use your favorite ORM to query the relational table, then row-by-row map each query result into an object. Remember, that’s the core of what an an ORM does: it maps relations to objects, and vice versa.

In the next step, you loop through your list of resulting objects, and one by one, convert them into relational data, to be displayed in a grid or table.

Wait… what?

That’s right. You used your fancy, general-purpose ORM library to automagically convert the relational data in your database, into an object. Then you wrote a manual, one-off ORM to map that object data back into relational data.

What a waste, right?

The only thing the ORM did was get in your way. And you probably didn’t even notice. You may have even said “thank you”!

Without an ORM in there, the translation from relational database rows to relational grid data is much simpler, faster, and less error/bug-prone. In fact, it may be as simple as appropriately naming the resulting columns in your SQL query (i.e. SELECT price_usd AS price).

Top comments (6)

Collapse
 
juancarlospaco profile image
Juan Carlos

I understand, thats why I made my own Compile-Time ORM.
:)

Collapse
 
jhall profile image
Jonathan Hall

Can you explain what you mean by "compile-time ORM"?

Collapse
 
juancarlospaco profile image
Juan Carlos

ORM that expands into low level database primitives at compile-time,
then at run-time it does not really exists anymore,
leaving only the compiled database primitives.

The kind of stuff that Nim lang can do with its powerful metaprogramming.

Metaprogramming is code that transforms the AST during compilation.
Code that codes code basically.

Thread Thread
 
jhall profile image
Jonathan Hall

The point of my original post is that converting from relational data to objects, back to relational data, is silly. Whether this is done at runtime, compile time, with metaprogramming, or in any other way, it still seems silly.

Collapse
 
l3lackheart profile image
l3lackheart

I dont get your point @@!

Collapse
 
jhall profile image
Jonathan Hall • Edited

In a nutshell: If you're using an ORM library to convert from relational data, to object data, then back to relational data, then your ORM library isn't serving any purpose.