Record Objects

Modern object relational mapping tools like Hibernate do very good job of decoupling domain layer from persistence concerns and bridging the object relational impedance mismatch. Yet there are times, either because of severe mismatch or when faced with inability to change database schema, we cannot map our entities to database tables without compromising on the design of one or the other. In such cases it is important to understand that ORM tools are really just mappers to objects. When these objects are not suitable to be used as entity objects we can always use hand written mapping approach. But this approach is riddled with problems which the ORM tools solve and they are more than having to write one's own SQL statements. ORM tools like Hibernate do more than just the mapping as they are complete persistence solution providing features like: lazy-loading, optimistic offline lock, unit of work to name some. Record objects solve this by having best of both worlds.

Record objects are new set of objects, part of infrastructure layer, which are mapped to database using regular ORM techniques. These simple objects per table easily map to the database. The repositories either themselves or by using separate mapper objects, map these record objects to domain objects. Since this mapping is done (or executed) by the repository the domain layer is now aware of the fact that entities are not directly mapped to the database. This pattern makes domain layer independent of a particular tool being used and the fact that the mapping abilities are not restricted by those of the ORM tool of choice. It still comes with an over head of mapping objects to objects and should be used only when required than as a consistent pattern everywhere in the code base.