
ORM is an anti-pattern - ExpiredLink
http://seldo.com/weblog/2011/08/11/orm_is_an_antipattern
======
ekidd
The post specifically complains about ActiveRecord, and claims that _the
abstraction of ORM breaks down not for 20% of projects, but close to 100% of
them._

This certainly doesn't match with my experience, and I've worked on dozens of
projects using ActiveRecord. Some of these were hairy production projects with
strict performance requirements and complicated schemas.

About 90% of the time, the ORM does the right thing. It creates, updates and
deletes individual records, and it generates entirely reasonable queries. And
it does this without requiring dozens or hundreds of lines of SQL.

You'll get much better performance out of ActiveRecord if you know a few
tricks, however:

\- Read the SQL queries in development.log to make sure they're sane, and use
New Relic to find slow queries in production.

\- Use 'include' to load a model and its associated objects in 2 queries
instead of 1+N queries.

\- Use 'select' to load only the necessary columns from your tables.

\- Don't try to force it: If you hit something weird, never hesitate to fall
back to SQL. ActiveRecord provides a dozen different places where you can
inject small SQL fragments into your queries, or you can just call
'find_by_sql' and do everything by hand.

If you start out with basic ORM models, benchmark your database, and add some
raw SQL as you scale, you can get reasonable rcesults with ActiveRecord. If it
breaks down for 100% of projects, you either have a weird definition of
"breaks down", or you're doing it wrong.

~~~
code_duck
"Don't try to force it: If you hit something weird, never hesitate to fall
back to SQL. ActiveRecord provides a dozen different places where you can
inject small SQL fragments into your queries, or you can just call
'find_by_sql' and do everything by hand."

I'm comfortable working like that, but it is exactly what the article is
criticizing. Sure, it works - but the whole idea of an ORM was supposed to be
avoding that.

~~~
Sapient
I believe ORMs want to save you from writing tons of repetitive queries, not
to save you from ever having to touch a line of SQL.

At least that is what I believe, I have never seen an ORM advertising itself
with "NEVER WRITE ANOTHER LINE OF SQL AGAIN".

------
ericflo
Here we go again. I'm pretty sure I've seen this post here (and the famous
Vietnam of Computer Science one) several times before.

No database access abstraction is going to be great for all situations.
Whether it's object-oriented, functional, or DSL-based, there are going to be
situations where it's frustrating to use. However, each of these abstractions
have a purpose and a clear benefit for a certain subset of situations, or else
they likely wouldn't have been created.

Since people find some abstractions useful for some subset of situations, why
waste so much time and energy fighting against its use entirely--labeling it
an "anti-pattern"? On the other hand, why waste time and energy arguing for
its ubiquitous use? Like with all other technology choices, the right
prescription is to use an abstraction when it makes sense, and to abandon it
when it does not.

Maybe it would be more constructive to frame the discussion in this way: what
cases are ORMs useful for, and what cases are they bad at? How can we identify
the good use cases from the bad? Which use cases seem to be good uses but turn
out to be bad, and why? What are alternative solutions for those bad use
cases? Are there different philosophies of ORMs with different tradeoffs? What
are those philosophies and tradeoffs and how can we choose which one most
suits our problem?

~~~
kunley
ORMs are useful for one thing for sure: for making an illusion that OO way of
thinking and relational way of thinking fits.

But they don't fit really!

I like the way original author explained it: the problem was that people were
forced or convinced to use wrong abstractions. Due to the massive marketing of
really big players since 80s, relational databases are everywhere around; most
of developers during the years took for granted that they MUST use SQL, so
they stopped thinking if they really need relational model.

Luckily we have other setting these days. There are plenty of production-ready
non-relational database engines. To simplify your application layer and really
_map_ your OO data, please do use document database - they fit. That's it. No
amount of pretending will dissolve the differences between relational model
and object-oriented model.

If in doubt, please go back to the theory, to the computer science. You don't
have to dig through tons of papers from 70s when relational model has had its
peak of scientific evolution - you just buy yourself the CTM book and go
through all the computational models with examples of the real code. Please do
the lesson. Otherwise any discussion will be about habits and beliefs again,
not about science and engineering.

And - I hate to say it - most of the comments like "here we go again" are
really about habits and beliefs. How sad. The foundation of our occupation is
hard science and engineering. We strive to build better things based on such
concrete foundation. By sticking to the thinking "OO + relations fit" we
abandon this foundation and we are turning into believers of some cult created
decades ago by the marketing people of the few companies everybody knows in
order to massively increase sales of RDBMSs. This is not engineering.

Please, put yourself in the distance from the habits of using specific tools
you're accustomed to; please think about it.

[edit typo]

~~~
acdha
So, say I do use a document database and object serialization is indeed easy
and fun again. Now I need to do reporting, only it's really slow until I
heavily denormalize (i.e. reinvent half of a SQL database and update every
time my reports change). Now I need to share data across objects so it turns
out I did need joins after all. Maybe I could invent an Object-Non-Relational-
Mapper to make some of that complexity easier to maintain…

None of this is saying a particular technology is wrong or bad but it's a
reminder that Eric was right to point out that they all have drawbacks which
developers should consider when picking a good fit for their application.
Blindly asserting that a particular one is good or bad is no better than
telling carpenters they only need hammers.

Even Google, for all of their massive resources and BigTable's deserved
respect, uses a ton of SQL databases - and they didn't add support to
AppEngine simply because they were unwilling to tell developers to try
something new.

~~~
smharris65
Can you cite evidence, other than anecdotal, that Google "uses a ton of SQL
databases"?

~~~
acdha
div's comment summed it up: one of the most useful MySQL patch sets floating
around was released by Google to help address scalability
(<http://code.google.com/p/google-mysql-tools/>) and this appears to have
continued until the present: [https://groups.google.com/d/msg/google-mysql-
tools/Bc7P5SIRC...](https://groups.google.com/d/msg/google-mysql-
tools/Bc7P5SIRCVE/ZfWMqCOxlDQJ)

I also know that they use at least one big financial reporting packages but
I'm not sure whether the use of Oracle Hyperion is evidence for or against
wisdom.

------
rickmb
The logic behind articles like this can be summarized as "trains are an anti-
pattern because you almost always eventually have to go somewhere where there
are no tracks or stations".

Getting tired of this. The fact that a tool or method has limitations and
risks doesn't make it an anti-pattern.

~~~
fauigerzigerk
The article makes a completely different point. It says, if you're travelling
from Moscow to Irkutsk don't take the train just because it departs an hour
earlier than the plane.

~~~
jvdongen
You are correct in that that appears to be the main point of the article.
However, the analogy is unfair.

Airports are in relative short supply, so once you've taken the train, your
stuck on it for quite a bit.

Migrating away from an ORM or using raw sql queries in addition to an ORM is
possible at all times (with more or less work, depending on the ORM you've
chosen). So you can start with the train and hop on the plane anytime you want
or need.

------
seldo
Hi! Author of the post here. Much as I'm happy to have this go around again,
this is actually a dupe, and has been very extensively discussed on HN before:

<http://news.ycombinator.com/item?id=2657745>

The reason it has a different URL now is a long story: my hosting provider had
a meltdown and I was less than religious about backups for my personal blog
(oh, the shame!) so I lost timestamp information on this and a few other
posts, as well as all the original comments. So it looks like I posted this a
month ago, but it's actually more than 3 months old.

Anyway, feel free to argue about this all over again -- it's new to you. I
just felt I'd post so nobody who remembers this the first time around thinks
I'm intentionally trying to game HN.

~~~
davesims
"Anyway, feel free to argue about this all over again..."

This was just as applicable when you first posted three months ago, Laurie. :
)

------
peteretep
And yet, DBIx::Class (and Class::DBI before that) daily make my life easier
over large, complex applications. The reason I use it is not because I was
told to by someone, but because it was a better way of doing what I'd find
myself doing in every bit of DB code I wrote anyway - abstracting the data
layer. DBIC does this in a predictable way that I know most other Perl
programmers will also understand.

So I'm sorry your ORM failed you. But there's no way in hell I'd ever go near
your codebase if you're shying off them in favour of raw SQL, but also because
talking about things as being 'anti-patterns' is ... urgh.

------
manuscreationis
She makes a bunch of great points, but as someone who has worked on several
projects with a properly implemented ORM, I find that I have to disagree with
the post.

It sounds like a lot of people who are Anti-ORM in the comments (here, and on
her blog), are focusing on the saturation of relational databases, and touting
that NoSQL style data stores are a better fit for certain problems.

No argument here

But in a relational DB, assuming you are using it for its intended purpose
(storing relational models, and not "objects"), I don't see why anyone would
want to eschew the use of a proper ORM, with the exception of incredibly small
projects with minimal database access.

For medium to large projects, I've never once regretted using an ORM. Not
having to write my CRUD statements? Having all of an objects relational data
lazy-loadable and at my finger tips? Sign me up! Just my experience.

I feel as though this author has worked in environments with other developers
who didn't "get" the benefits of ORMs, and thus the implementations of those
ORMs suffered. This is just my opinion from what I've read. I could be wrong
here.

Death by a thousand queries, however, is a completely valid complaint. In
fact, it's my one of my only major gripes with ORMs. But maybe I've just never
run into these cases that the author has that makes ORMs so unbearable to use.
Maybe i'm just lucky?

Also, she re-blogged this from several months ago:
<http://seldo.com/weblog/2011/06/15/orm_is_an_antipattern>

------
guard-of-terra
ORM is bad for reporting and complex queries, but it makes CRUD bearable. The
amount of code required to write CRUD subroutines for every kind of data
present in database tends to bore absolutely to death, with endless realms of
near-copypaste code. Any good programmer would throw together a half-baked ORM
just to DRY database access code.

~~~
andybak
"ORM is bad for reporting and complex queries" - all ORMs?

I've heard SQL Alchemy is pretty hot at that kind of thing.

------
polemic
I don't particularly disagree with anything in that post, but the fact is that
the code time saved with an ORM is so massive, that NOT using one is
effectively gross premature optimization.

Sure, as your app grows, you write SQL to speed up the bottlenecks. And that's
O.K.

~~~
jawher
It depends on the ORM you use, but I'm afraid it's not as simple as "you can
later hand write SQL queries to speed things up". This will interact badly
with the ORM's cache/transaction handling: your select queries won't see
uncommitted changes held by the ORM, and even worse, your ORM won't see the
modifications you made with insert/update/delete SQL queries.

Also, one of the pro ORM arguments is that it generates database-specific SQL,
making your code theoretically portable between different RDBMS. Hand writing
SQL will break this.

Another point: your ORM would automatically pick up changes to your model and
cope with it, not your hand-written SQL, making your code harder to maintain.

~~~
div
>> It depends on the ORM you use

Yes, some ORM's are more flexible than others.

>> ... one of the pro ORM arguments is that it generates database-specific SQL
... portable between different RDBMS

Yes, hand writing SQL will break this but:

\- it is rare in my experience to completely migrate to a different RDBMS

\- migrating to a different RDBMS should easily be viewed by everyone from
management to development as a very tricky process that will take time to
perform correctly. Part of this time will be tuning your custom queries.

\- the ORM promise that it's queries are RDBMS independent is not broken

>> Another point: your ORM would automatically pick up changes to your model
and cope with it, not your hand-written SQL, making your code harder to
maintain.

Writing everything by hand (known alternative 1 from the article) makes your
code even harder to maintain because there will be zero changes that are
automatically picked up.

Depending on the KV store you use, his second alternative may not have this
problem.

TLDR: Hand writing sql comes with a cost, but the overal cost of "ORM + a bit
of handwritten sql" is likely to be much less than "everything handwritten".

~~~
regularfry
In general, people don't migrate between databases. In specific, I find myself
migrating from sqlite to either Mysql or Postgres relatively frequently.

~~~
jawher
That depends on what kind of products you make: If it's a website, then you
have absolute control over what stack and database to use. But if you're
selling any kind of app that needs a database, then you'll need to support
different databases. Some customers won't ask questions and take your default
database, others (unfortunately ?) will want it to use their Oracle/SQLServer
installation that cost them a bazillion.

------
stefanobernardi
Nonsense. Everything is overridable. ORMs are perfect for a whole lot of
standard cases and nobody prevents you from writing SQL code for custom cases
and performance improvements.

~~~
apsurd
we use Datamapper at work and have an increasing need to write custom sql
queries. A common problem we face is that we now have non-standardized data
coming out of the model. In other words does this method return a datamapper
object or is it an array of custom-defined fields ? a quick fix would be to
use the custom query to return ids and then use those ids to perform a
Datamapper query that returns DM objects - which is clearly not a good
programming practice.

In my experience this article is spot on. It's easy to say "oh sure just use
custom sql for this _edge case_ " Only those edge cases turn out to be
increasingly common and it is increasingly hard to work with data that may be
coming at you in multiple formats.

~~~
Daishiman
The problem is that, plainly, your ORM sucks. Serious ORMS allow you to inject
custom SQL and still return objects; many can just take the result of a plain
SQL query and map it to objects as you please.

Really, there are good and bad ORMs. Bad ORMs produce the results you mention.
Good ones are much more adaptable.

~~~
dkubb
The DataMapper ORM allows you to use SQL but still return domain objects:
[http://rubydoc.info/github/datamapper/dm-ar-
finders/master/D...](http://rubydoc.info/github/datamapper/dm-ar-
finders/master/DataMapper/Model:find_by_sql)

Maybe the gp doesn't know about it or chooses not to use it, but it exists.

~~~
apsurd
thanks for this! You are right I had no idea this existed. Just goes to show I
really should read the source over depending on datamapper.org/docs/ too much.

------
sreitshamer
Instead of trying to use a relational database in an OO way, maybe it's better
to go the other way and make code fit the relational model better. Databases
(and the data within them) often far outlive software.

~~~
hughw
Ideally we'd have languages impedance matched to making assertions and queries
in the logical language of relations. Prolog? (Googling "Prolog SQL" turns up
this Stack Overflow discussion about translating Prolog to SQL
[http://stackoverflow.com/questions/724377/prolog-to-sql-
conv...](http://stackoverflow.com/questions/724377/prolog-to-sql-
converter/1682486#1682486))

------
geebee
I wouldn't go so far as to describe ORM as an anti-pattern. I'd rather just
say that I'm more productive in the long term without it. Like the author of
this post, I always eventually end up dropping raw sql to get things done.

I don't even think necessarily much of an initial productivity boost. SQL
doesn't take all that long to write, and once you do, you have complete
control over your app.

I'm not completely sure what's meant by the statement "Use SQL in the Model."
I think I agree, though I'm hoping this doesn't mean including SQL in the
model class itself. I'd avoid coding references to how an object will be
persisted in the model class itself. I'd lean toward creating a DAO (or some
other API for persisting/retrieving an object) that you can use/call without
worrying about how it is happening. The difference is that I'd rather
implement that API through SQL than through an ORM framework.

------
exogen
ORM isn't a pattern. Most people complaining about ORM libraries are
complaining about Active Record. I thus automatically assume anyone making
this claim is misinformed, and roll my eyes.

Active Record is a pattern. Ruby's ActiveRecord and Django's ORM are
implementations of that pattern. The Active Record pattern has some of the
problems mentioned in this article, with convenience being the major benefit.

Data Mapper is another pattern. Python's SQLAlchemy and Java's Hibernate are
implementations of that pattern. These will get you a lot farther without
bumping into limitations. And honestly, I've written some terribly ugly
queries in SQLAlchemy and it still worked. I've even started with an ugly
query I wanted to make in raw SQL and then made sure that it was possible
using just the library and no SQL strings.

------
zzzeek
Why does this old junk keep getting reposted? Is someones boss making them use
an orm against their will? Go work somewhere else and stop dumping on our
tools.

~~~
j_baker
Let's be fair for a moment. Now I admit to skimming the article, but it sounds
like the author is more complaining that he hasn't seen an ORM implementation
he liked. Perhaps he hasn't used SQLAlchemy yet. :-)

I'm not saying that to be snarky. If I hadn't used a good ORM like SQLAlchemy
(although I'm sure there are others out there), I'd be inclined to agree.

------
davesims
Laurie, this is a good restatement of the age-old problem of Object/Relational
impedance, the perennial bugaboo of many an architect, developer, and DBA.
It's true that ORMs are merely bandaids on what is essentially an intractable
set-theoretical problem, but we've learned over the years that in the right
hands an ORM is a tremendous productivity boost, provided the team is aware of
the limitations. In fact Martin Fowler's original definition of the
ActiveRecord pattern in Patterns of Enterprise Application Architecture
describes some of these limitations from the very beginning.

"Unfortunately, these advantages disappear as the project increases in
complexity: the abstraction breaks down, forcing the dev to use and understand
SQL"

"Forced" to use and understand SQL? I think you have a basic misunderstanding
of the purpose of ORMs, Laurie. The developer who can't use and understand SQL
really has no business going near the ORM. They probably need to stay
somewhere near the front-end doing design, layout and UI-centric work.

The purpose of an ORM, properly used, is _not at all_ to completely remove SQL
from the developer's toolkit, but to help developers who fully understand SQL
and Objects eliminate boilerplate SQL. This has a huge dual benefit of
productivity boost plus elimination of bugs by the reduction of code/SQL
duplication.

If an ORM developer is not aware of SQL (i.e., watching their rails log for
odd queries/joins) and the natural problems that arise, such as n+1, etc. then
they probably shouldn't be writing data-layer concerns. ORMs are for
experienced developers who know how to use things like the ActiveRecord or
DataMapper DSLs when appropriate, and can also drop into straight SQL when
appropriate. ORMs are power tools for serious developers who can use them for
what they do well, and know how to avoid their weaknesses, which you outline
well here.

Because of their benefit and the cumulative experience we've had in the last
10 years or so getting to know _how_ to use ORMs effectively, they're not
going away any time soon. However, they certainly have their pitfalls and it's
important that we have posts like these every few years or so to remind us
what those pitfalls are. So thanks!

~~~
j-kidd
> The developer who can't use and understand SQL really has no business going
> near the ORM.

Absolutely. First we have developers trying to use ORM (a.k.a. HideSQL) to
avoid learning SQL. That fails. Now we have developers trying to use NoSQL to
avoid learning SQL. This "avoid learning SQL" thing is shaping up to be a
fantastic anti-pattern. I wonder what's next.

------
wildjim
Years ago, before ActiveRecord, I started writing my own ORM for Ruby. I got a
reasonable way into it, too. I gave it up, because I realised that it was
much, much simpler to write many small PL/SQL views and write-triggers and use
temporary local objects and/or lazy writes (etc). The DB could do much better
query-optimisation this way, for one thing. But anyway, that was a long time
ago.

TBH: If you want all your relational logic in your app, NoSQL systems make an
awful lot more sense these days -- esp. if you've got a decent API/wrapper-
layer that can automatically manage the freshness of locally cached data for
you.

------
tychobrahe
Somebody correct me if I'm wrong, but aren't most of those complaints related
mostly to the SQL generation rather than the "mapping" part?

I find that the problem when discussing ORMs is that we gave them two
completely different responsibilities: generating queries and mapping the
results... In fact, those two are already separated in Rails (AREL?).

I don't see much of a criticism to the mapping part (and the benefits given to
you in form of validation/metadata/migration/schema versioning)... In fact,
unless you're going to access the records directly via the database driver API
(giving way to hideous coding), you'll probably reinvent the wheel or do the
O-R mapping by hand to fill POCOs/POJOs/etc, as I've seen on so many
enterprise projects (in different levels of elegance).

But then, again, somebody please correct me if I'm wrong.

------
neeleshs
ORMs leak abstractions? Yes. ORMs are an anti-pattern? Thats a little hard to
swallow. As many people have pointed out on this thread, I use ORMs as just a
tool to avoid writing the darned boilerplate code. As many times I have
started writing simple code to abstract the boilerplate, I inevitably endup
writing a half-baked ORM tool, at which point, I throw it and just use an
existing one. The key advantage for me is not that it abstracts SQL, it does
not do it at all, but that it abstract so many other unimportant details that
I must solve to fix the "impedance mismatch" between two different systems -
an OO language and a relational system. I use an ORM to do just that.

------
iradik
The thing with ORMs is they generally are really more like data structs than
full-on objects, but ORMs cause some devs think that's what objects are. When
in fact an object is just a bundle of capabilities. While the ORM operations
(select, delete, etc.) are capabilities, they don't specifically model the
capabilities of the system, and in fact many times these operations should be
unexposed outside of the object.

------
josteink
He lost me when he constructed a false problem by claiming that the result of
a query sent through the ORM has to result in discrete objects mapping 100% to
the "base-form" of the objects, ie their table-based definition and that this
causes immense problems when you have relations and dependencies based on
those.

In C#, using LInQ I can specify exactly what columns I want, how I want things
joined, and how the resulting object should composed, without the need for
adding additional named classes or augment my data-model. I get control of
what gets sent to my DB and I get only the information I need returned, in the
form I desire. And I certainly hope that C# still qualifies as an OOP
language.

His rant seems to be that inadequate ORMs is an anti-pattern. But isn't
investing anything in something you know to be inadequate by definition an
anti-pattern? He is making his own circular argument and then trying to sneak
up the scope beyond what is valid.

Needless to say, I think his argument is simplified, based on dated
information and this invalid.

------
liljimmytables
Hand-coding and maintaining bog-standard glue logic at the start of a project
isn't good either. Auto-generation of database and glue logic for your app is
possible, and the task usually falls to an ORM. The problem as described is
that the glue logic is trying to hide the implementation, making it hard to
remake the code when it becomes clear that the out-of-the-box implementation
is not appropriate.

This doesn't seem like an insoluble problem; rather than use an ORM to
generate an impenetrable glue layer, it would be better to use code generation
tools to create a clean database model and a glue layer that can be easily
overloaded as required.

What tools exist that give you ORM-esque generation at the start of your
project, but allow you to do maintenance on the glue layer later in the
project?

~~~
jawher

      > This doesn't seem like an insoluble problem; rather than use an ORM to generate an impenetrable glue layer, it would be better to use code generation tools to create a clean database model and a glue layer that can be easily overloaded as required.
    

Glad you brought that up. I too thought about this as a middle ground solution
between "boring your self to death by writing dozens of SQL queries and hand
mapping to your model" and "black box ORM that generates crazy SQL queries".

I'm not sure it would work though. One of the problems I see is inherent with
code generation approach: what happens when you had to modify the generated
code and then changed your meta-model and want to regenerate the model again ?

Besides, the problem of "fitting square pigs in a round hole" would remain:
SQL is much more versatile and flexible than objects/structs: you simply can't
just work with the a table=an object abstraction, which tends to yield
inefficient database queries and/or headaches from the developers side.
Example:

    
    
        update table set one_field=value where some_condition_on_another_field.
    

How would you expect an ORM to generate a "dense" query like this with it's
simplistic view of things ?

The same applies for the select queries, especially for reporting and data
aggregation needs, where you would select some columns from multiple tables,
possibly with formulas and computed columns.

~~~
j-kidd
> SQL is much more versatile and flexible than objects/structs

SQL isn't even turing complete. How can it be more versatile and flexible than
your programming language of choice?

> How would you expect an ORM to generate a "dense" query like this with it's
> simplistic view of things ?

In SQLAlchemy,

    
    
        cls.query.filter(<some_condition_on_another_field>).update(dict(one_field=value))

------
yason
I think the problem per se isn't treating rows as objects and just querying
one row to read the data for one customer or transaction or whatever. I think
that the taxing problem comes from fitting these _records of data_ into an
overly _object-oriented style_ of programming, and feeling the pain when
you're actually hitting into this mismatch.

Then you might go all the way and try to abstract away the fact that you're
reading a record from a database. For what, I don't know, but it feels often
that there's some perceived benefit in pretending that everything, including
data, is a native object and all objects are alike--even if you have a heavy
marshalling mechanism to prove that isn't the case.

------
mattchew
Hear hear.

Also, learning a different ORM every time you switch environments is costly.
Switching from, say, Django to LINQ2Entities has nearly no knowledge transfer.
Dealing with the quirks between MSSQL, postgres, MySQL is comparatively
simple.

------
dools
It's definitely just ActiveRecord and not ORM that cause the problem in my
opinion.I've started work on an alternative which focuses on automating just
the most tedious parts of writing sql then getting out of the way (and
requires no boilerplate classes - it intuits the relationships from the key
names). Oh and it's fast as hell and uses very little memory.

I call it PluSQL: the ORM for SQL lovers:

<http://github.com/iaindooley/PluSQL/>

------
darylteo
I am very much liking Entity Framework's Code-First process. Instead of
generating code to match a relational database, generate a relational database
to match my object model. (So you have full control over what your data
objects does)

Combine that with LINQ and you have a 80-90% coverage of complex joins.

Also combine it with CQRS principles and I hope that when my project requires
scaling (and I so hope it does) then I can easily scale

~~~
emp_
This. CQRS is the place ORMs truly shine.

------
jwingy
I don't have a ton of experience with ORM, but I've always wondered how much
time is saved trying to abstract SQL queries away from SQL when SQL is
supposed to be relatively easy for most people to get into. At least for the
simple use cases that ORM is supposed to be good at, the SQL equivalent should
be simple as well right? Or am I not quite understanding the benefits of ORM?

~~~
jawher
It's not just the SQL. There's also the mapping code between your objects and
the SQL. for instance, for a select query:

    
    
        select first_name, last_name, login, email from users where id = 5;
    

Depending on the language and ORM you use, you'll need to write code that
resembles this:

    
    
        result = execute(query);
        User u = new User();
        u.firstName = result.get("first_name);
        u.lastName = result.get("last_name);
        u.login = result.get("login);
        u.email = result.get("email);
    

The mapping part may also involve data conversion between SQL types and you
language types.

The same also applies to the other direction: when you want to generate an SQL
query that updates/inserts an object of yours into the database.

ORMs also handle (I didn't say well) relations between objects (1..1, 1..n,
n..n).

------
benmmurphy
after being forced to write a crud app using just stored procedures because of
'performance reasons' and 'security reasons' (n+1 queries and queries with sql
injection problems were still written including by the person who mandated
this) i don't really like people writing articles like this. even though it
may be true in some cases it just gives ammunition to idiocy.

------
EGreg
This article has one main point that I have come to agree with. If you are
using an ORM, consider that you should actually be using a NoSQL database
instead of a relational one.

It may be the case that you don't, but really -- if what you want to do with
objects is retrieve them, modify them, and save them, then a key value store
is more like what you need.

------
voidr
I find the author to be looking at ORM the wrong way, the way I see it: ORM
just gives you basic features that you would probably write yourself, you
still have need SQL for more complex stuff.

Basically it's just a standard way to do the basic stuff.

If you want optimized select queries, you can still write them, also inserts
are optimal with ORMs.

~~~
jeltz
Inserts are not at all necessarily optimal in ORMs. Inserts can be just as
complex as select queries, since they can include arbitrary select queries. A
trivial case of that being.

INSERT INTO a SELECT * FROM b;

I personally have not felt the need to use and ORM yet. But then I have not
built a CRUD heavy app either. Instead most of my time spent on database work
is centered around reporting and other complex queries where no ORM I have
seen yet helps much.

------
Produce
The answer is obvious - use an ODBMS instead of an RDBMS. No more imedance
mismatch. The issue is that there hasn't been as much development,
particularly high quality OSS projects, of this type. For example, I can't
even find one for PHP.

------
kqueue
You cannot render a pattern useless because you had a bad experience with
certain implementations.

The pattern represent a very good abstraction concept that is irrelevant to
the library implemtation.

------
schiptsov
In the good old times, when sky was more blue and trees were taller, there was
two almost distinct approaches to use SQL database. They call them OLTP and
Data Warehouse. Some vendors, such as Informix or IBM even offered a different
products for those two segments. The firs one, as one can understand from its
name, is about fast and reliable online transaction processing, which means
triggers and stored procedures and loads of small queries, mostly inserts or
updates. Now all those no-fsync options and noSQL and mem-caching solutions
solve similar problems their own way. You can have a thousands of writes and,
if your system never crashes, with some data consistency (and forget about
triggers) In old good times Informix Dynamic Server was the answer.

Data Warehousing is all about JOINS, big JOINS. Or that thing they call it
data-cubes. In that case you need query optimizer, lot and lots of buffers,
data partitioning and several layers of caches. You also should use stored
procedures, because it is a good way to structure and manage your code, same
way modules work for other languages. So, you know, that old lovely DB2.

Even in old times, people who claims that there is a solutions that fits both
cases were considered crazy. That is why no sane person considered MSSQL
(leave alone MySQL) as something other that a taste-less joke.

Nowadays people forgot about designing in terms of data flows. Everything
starts with installing some framework, such as Spring+Hibernate, Rails or some
PHP crap. They forgot that not tables itself, but queries (which type, how
often) to them is what matters, that indexes optimized for actual query flow
is what performance of a server is all about, and that actual structure of
tables (and corresponding indexes) must be adapted/redesigned for that
particular production flow of data. That was a DBA's job.

Today some people believe that they can eliminate smart but costly engineers
(DBAs or sysadmins) by some software which is marketed to them as Easy, Smart,
Fast, Zero-thinking or whatever - ready meals for a mediocre crowds. OK, if
you're building a 20 pages web-site for a 100 visitors per day, that might
work - you can save some money and time, but, if it is a industrial or
internet-scale solution, there is no chance that you can run Rails or say Code
Igniter crap in production without huge changes or total redesign. No fucking
way.

So, all those specialized solutions, such as memcached, redis, membase,
mongoDB are about dealing with flows of technical data, such as AJAX queries
from UI, logs, authorization requests, chats, photos and other unimportant
things, OR about building a huge distributed cache layer above actual data
store. But, of course, you cannot build a Data Warehouse out of it. (Or invent
a complete different approach to dealing with data, such as map/reduce).

So, ORM is anti-pattern? It is not efficient? Ridiculous. It is just broken by
design. ^_^

------
based2
A kind Cathedral against Bazaar :-)

------
middayc
Great. One more guy that gets it.

~~~
ExpiredLink
'We' will continue to grow.

------
adelevie
dhh, tenderlove, wycats: purveyors of an anti pattern!

In all seriousness, I'd love to see a criticism of ORM that takes Arel into
account
([http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-...](http://magicscalingsprinkles.wordpress.com/2010/01/28/why-
i-wrote-arel/)). I have yet to see one.

------
space-widget
so obviously false.

go read martin fowler's _patterns of enterprise application architecture_.

------
getonit
Beautifully explained.

