July 12, 2011

Hibernate vs. Active Record

The following is a bit of an opinion piece on the relative merits of Hibernate vs. Active Record. Before I start, here are the cliffnotes on both: Hibernate lets you focus on the code and takes care of the database, Active Record lets you focus on the database and takes care of the code.

I have been lucky to get to build up some real world experience with Hibernate. I've also played around with Active Record in some Rails apps. Up until a few weeks ago I would have said that the approach either takes is mostly one of technological preference. And to some extent that's true. You can do pretty much whichever you want with either.

Yet I have come to think that Active Record has got it right, and Hibernate doesn't. Here are my two reasons.

Flexibility.

In Hibernate the database is generated from the code. All data enters the database as instances of the model classes. If, however, you want to map something else to/from the database you are always stuck with having to go through objects (or code SQL statements manually, which is basically bypassing Hibernate altogether). This is not necessarily the most efficient solution.

In Active Record the model is just a view on the database. There's nothing keeping you from mapping the database to another model, and so you can conceivably store and fetch your data in any format you want, without having to instantiate the model. So if you want to populate your database based on data in an XML format and later retrieve your data in some form of CSV, you can.

Note/Caveat: I don't know if the Active Record implementation in Rails supports this, or if there are extensions which allow this. But I don't see why it couldn't be done.

Broken promise.

Hibernate kind of lets you believe in a fairytale when you start using it, and it's one that's especially appealing to programmers: that it will take care of the database for you. Just set up the connection parameters and you're off. The problem is that this promise breaks as soon as you want to store more than some of your mother's recipies. Getting the database right is a crucial part of real software systems. So in the end you'll be working on fixing your database and updating the annotations in your code to match.

With Active Record, however, the database is the central entity and you can work on getting it right. From there it generates the code, and you're mostly left with fixing some broken methods if your changes are incompatible. To me that's a much more attractive road to walk.

Just to be clear

I don't think that Hibernate is bad. It's not. It gives you a lot of power to get your applications going. I have used it before and I'll use it again. But I do feel that when it comes down to it it's actually Active Record which has the edge.

No comments: