Open debate: when does ORM make sense?
Twice recently I have found myself trying to convince someone that Hibernate, and ORM tools in general, were a poor fit for database access. ORM has advantages and features that can make it difficult to use.
Factors that determine whether ORM is a good choice
- The application works with multiple database types. Here, ORM offers invaluable help with portability. It may be imperfect, but it certainly beats the work of porting the data access layer to N more database types.
- The application needs to read and write rich object structures. ORM will not save us from writing queries here, but it saves a pile of code for processing them. I mainly mean the code that walks a ResultSet to build an object tree and, in the opposite direction, the code that walks an object tree to build a PreparedStatement.
- The application can afford to change its RDBMS schema to suit object-relational mapping. Hibernate can work magic mapping just about anything onto anything, but it is better to adapt the RDBMS schema to fit.
ORM frameworks are easy to adopt initially. They work very easily with sample schemas. You need to map a one-to-many relationship, or get an entity by its ID. I think that ease and database portability are the shiny bits that lure a lot of developers in. Unfortunately, there is also a dark side to the Force. You have to reckon with it and take care when you do.
I would put it this way. If nobody on your team has experience with ORM, you are in for plenty of unpleasant surprises. ORM is complex and you probably have no idea what is under the hood. The first rude awakening comes when you turn on SQL logging. A LazyInitializationException follows, and it ends with mysterious writes to the database that make no sense to you.
That awakening and the headache come from the complexity of ORM. As well as learning the framework's own language, you have to absorb and understand that complexity. Just as there are design patterns for object-oriented design and enterprise systems, there are patterns for using ORM successfully. Believe me, you have a problem if you do not know them.
I would hate for this article to give the impression that ORM is bad. Like any approach, it suits some jobs well and others less well, and some jobs are unsuitable for it altogether. The obvious question is what else to use. The iBatis framework is a fairly good compromise between complex ORM and low-level JDBC. See, for example, Honza Novotný's iBatis 3.0 preview — part one. You map an object graph to SQL queries instead of tables.
I would be delighted to hear your views and experiences with ORM in the comments.
Related articles
Related CZ Podcast episodes
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio
- #1 · Vývojová prostředí v Javě
The first CZ Podcast episode looks at Java development environments. · Czech audio