DEV Community

Discussion on: Explain ORM like I'm five

Collapse
 
dmfay profile image
Dian Fay • Edited

I'm the database. I have data organized into related tables: there is a stables table with addresses, capacity, and so forth; a horses table containing names and vitals and a link to the stable quartering the horse; a riders table containing other names and other vitals; and a horse_riders table linking individual riders to individual horses, since a rider may switch out or share horses. There's also a statistics table with event names, times, and awards for a given horse; each record is a separate event.

You're an application which displays horse data and allows users to edit and create more horse data. You need to talk to me in order to make that happen.

There are a few ways of accomplishing this. Object-relational mapping is one of the more common approaches but is by no means unambiguously the best (it's been called "the Vietnam [War] of computer science") and I tend to agree with that characterization).

With an object-relational mapper, you think about how you want to work with horse data and create a set of models which loosely correspond to my schema. You might combine the horses and statistics tables into your Horse model, for example, and will likely not even consider the horse_riders junction table at all -- the O/RM abstracts that part away for you. Your Stable object even has its own collection of Horses attached, which can be eagerly or lazily loaded with little to no effort on your part! This loose correspondence is what we call the object-relational impedance mismatch: a Horse with its own statistics may be easier to work with in the application context, but it's different from how the data are actually represented. This saves time in the short term but makes adaptation much more difficult. When (it is not a question of "if") you need to do something you didn't originally account for, you will wind up doing one of two things:

  • major surgery on your data model
  • writing SQL, the thing the O/RM was supposed to do for you

This is not to say that object-relational mapping is without advantages. It makes the first 90% of data access pretty straightforward, especially if you're using an object-oriented language. And it tends to use lowest-common-denominator functionality of the database, if supporting multiple engines is a pressing concern. But I don't feel that those advantages outweigh the inevitable drawbacks, especially when there are alternatives like the data mapper pattern.

Collapse
 
jaro0024 profile image
Dani Jaros

That helps! Thanks!