Rich domain models imply rich object relationships, but rich relationships are often hard to implement when objects are initialized from a database. Johannes Brodwall's recent article explores how lazy-loading techniques can help you have both rich object relationships and maintainable, high-performance code.
When developers first start out with an object-relational system, such as Hibernate or the Java Persistence API, the initial reaction is often relief, since the framework takes care of initializing object state from the database, as well as persisting object state back to the database. As soon as more complex object relationships are persisted, however, the performance drawbacks of a naive O/R mapping approach become apparent.
One reaction to the difficulty of working with a rich object model is to flatten that model to suite the needs of the O/R framework. While such an approach can result in performance gains, it defeats the benefits of efficient OO design.
In an interview with Artima at the 2005 JavaOne conference, Hibernate project lead Gavin King highlighted the importance of data access objects (DAO) in the context of using that O/R mapping tool. Among other features, data access objects have the ability to load data lazily.
In a recent article, Lazy Loading is Easy: Implementing a Rich Domain Model, Johannes Brodwall dives into the details of lazy loading, with and without an O/R framework. From a simple DAO-inspired example, he proceeds to detail defining and creating lazy loading interfaces, classes, and collections, and then discusses the issue of referential integrity in lazy loading.
In addition to simple lazy loading, he discusses the problem of one-to-very-very-many relationships, and shows how to use paging, holding only a subset of objects in memory at a time.
Brodwall notes that,
...The ORMs available today do not even attempt to solve the one-to-very-very-many relationship. You can use the approach I showed with ORMs just as easily as with JDBC. If you create your own TopLinkCategoryDAO, use TopLink as normal, but instead of mapping subcategory, add a subcategory paged collection to the newly created objects. Maybe your domain model has a file name that references a file on disk. Why not make it into a lazy relationship? And if you're an ORM developer reading this article: please, the one-to-very-very-many relationship problem is [a] real need, and you can solve it.
...You might also be using [a] technology like JavaSpaces, which as far as I know does not support an ORM-like approach for lazy loading relationships. Again, I also wish the vendors within this space ... will start [addressing] lazy loading more.
What's your approach to mapping complex relationships when using an O/R mapping framework?