Home > Articles > Data

  • Print
  • + Share This
This chapter is from the book

Using Metadata

In this book most of my examples use handwritten code. With simple and repetitive mapping this can lead to code that's simple and repetitive—and repetitive code is a sign of something wrong with the design. There's much you can do by factoring out common behaviors with inheritance and delegation—good, honest OO practices—but there's also a more sophisticated approach using Metadata Mapping (306).

Metadata Mapping (306) is based on boiling down the mapping into a metadata file that details how columns in the database map to fields in objects. The point of this is that once you have the metadata you can avoid the repetitive code by using either code generation or reflective programming.

Using metadata buys you a lot of expressiveness from a little metadata. One line of metadata can say something like

<field name = customer targetClass = "Customer", dbColumn = "custID", targetTable = "customers" lowerBound = "1" upperBound = "1" setter = "loadCustomer"/>

From that you can define the read and write code, automatically generate ad hoc joins, do all of the SQL, enforce the multiplicity of the relationship, and even do fancy things like computing write orders under the presence of referential integrity. This is why commercial O/R mapping tools tend to use metadata.

When you use Metadata Mapping (306) you have the necessary foundation to build queries in terms of in-memory objects. A Query Object (316) allows you to build your queries in terms of in-memory objects and data in such a way that developers don't need to know either SQL or the details of the relational schema. The Query Object (316) can then use the Metadata Mapping (306) to translate expressions based on object fields into the appropriate SQL.

Take this far enough and you can form a Repository (322) that largely hides the database from view. Any queries to the database can be made as Query Objects (316) against a Repository (322), and developers can't tell whether the objects were retrieved from memory or from the database. Repository (322) works well with rich Domain Model (116) systems.

Despite the many advantages of metadata, in this book I've focused on handwritten examples because I think they're easier to understand first. Once you get the hang of the patterns and can handwrite them for your application, you'll be able to figure out how to use metadata to make matters easier.

  • + Share This
  • 🔖 Save To Your Account