Welcome!

.NET Authors: Tad Anderson, Ivan Antsipau, Liz McMillan, Pat Romanski, Matt Hester

Related Topics: .NET

.NET: Article

The OO Database Advantage

Painless object-oriented databases

Here's a question: If you write your application's code in an OO language - such as C#, VB.NET, or managed C++ - why not write database query and update code in the same language? It would certainly make life simpler, wouldn't it? At the very least, you'd only have to hold one language in your head - not your programming language and SQL.

That's the very least of the advantages you'd gain by choosing an OO database instead of an RDBMS. The metaphor "impedance mismatch" has frequently been used to illustrate the problems that arise from using a relational database as the back end to an OO application. Admittedly, it's a somewhat overused metaphor, but it still serves its purpose. It illustrates the fact that relationships among objects - referencing, containment, polymorphism, and so on - must be translated into relational constructs when those objects are stored in the database. Furthermore, the translations require developer intervention at some point: either explicitly in executable code, by creating schema mapping files that a translation layer reads and interprets, or through some other mechanism.

The upshot is that you have to "explain" the object structure of your application to a relational database - and in terms that the relational database understands. Sometimes this even requires you to add elements to one or more of your objects - elements that translate to additional columns in one of the RDBMS tables, and serve no purpose other than to support object relationships.

Specifically, suppose you have an OO application whose objects' structures exhibit a tree-like or networked arrangement. With regard to entities that your program can treat as a single (albeit complex) object, the back-end RDBMS must distribute across multiple rows and (likely) multiple tables. For example, deleting a single tree - which in OO code would be the mere dropping of a reference - turns into multiple delete operations on multiple tables. (Source code for this article is available from www.everylittlething.net/PartsAssembly/.)

Illustration by Example
Suppose you must write an application for an assemblies database - that is, a database whose content tracks items that are assembled from "parts." A "part." in this case, could be just about anything: a screw, a light bulb, a spring, or even a software component. It doesn't really matter: the idea is that assemblies are constructed by connecting parts together, and in turn, more complex assemblies can be fabricated by connecting assemblies together.

The aggregation of lower-level assemblies continues until a top-level assembly (or a "finished product") is reached. Therefore for example, a motherboard assembly - consisting of circuit board, CPU, and memory part objects - is combined with a power-supply assembly, a disk-drive assembly, and a chassis assembly to create a desktop system. This structure is illustrated in Figure 1.

This kind of database is nicely portrayed in an object-oriented structure. The Part class is the fundamental building block. From it, one derives a PartAssembly class (which models an Assembly from Figure 1, but which we renamed in order to sidestep any confusion with .NET's meaning of the word "assembly"). The PartAssembly class extends the Part class by adding an ArrayList collection of components. Members of the components collection are required to assemble this PartAssembly.

If we strip away the method definitions for these classes, the structure becomes transparently obvious (see Listing 1). When implemented in a relational database, the class structure in Listing 1 would require two or three tables, depending on how a person modeled the inheritance relation.

In a three-table arrangement, Part objects would be stored in one table, PartAssembly objects in a second, and the contents of the components ArrayList in a third. (This kind of mapping from OO to relational is referred to as "horizontal mapping.") The column structure of the Part and PartAssembly tables would be identical, because the only difference between the two - the components element in PartAssembly - would be stored in the third table. The components dictionary table would hold two columns, one for the Part, and a second to reference the PartAssembly identifier. This second column is a foreign key, and provides the connection between the components and their "owning" PartAssembly object.

In a two-table solution, Part and PartAssembly would share the same table (this is known as "filtered mapping"). That table would include columns for category, name, manufacturer, and manufacturerPartNumber. An extra column would be added - call it classID - that would be used to distinguish rows that correspond to Part objects from rows that correspond to PartAssembly objects (see Figure 2).

The advantage of the three-table mapping strategy is its conceptual simplicity. Each concrete class gets its own table. It is also more easily extended. If, for example, a new class were defined that extended PartAssembly, the developer would need only to construct a new table.

On the other hand, the two-table strategy has the advantage of minimizing the number of tables required. However, adding a new descendant class to either Part or PartAssembly (with new data members) would require adding new columns to the table, as well as new logic to identify the additional class type.

Simplicity Calls
Wouldn't it be nice if all this discussion of mapping strategies were unnecessary? As we've stated already, this sort of class structure is easily modeled in an OO language. It follows that the ideal situation would be if that easy modeling were simply extended to the database. Put another way, our object structure's schema is built into the very architecture of our class definitions. Why should we have to create yet another schema for the back-end database, and then build a mapping layer to translate data from one schema to another? Wouldn't it be nice if we could simply design our classes, write our application, and store objects right into the database "as-is"?

With an OO database, we can. For the remainder of this article we'll demonstrate how to do this by using an open source database, db4o. Microsoft .NET and Mono versions of db4o are freely available from www.db4objects.com.

Assuming that we have defined the Part and PartAssembly classes as above, and that the path to our database file is in string variable filename, we can store Part objects into a db4o database with the code in Listing 2.

This is more like it. Rather than clutter our application with SQL code flanked by assignment statements that pass object contents into bind variables, we have a single call to a set() method. Most important: notice that we did not have to describe the structure of a Part object to the db4o database engine; it deduced that information itself, via reflection.

Also notice that db4o invisibly began a transaction for us. The db4o engine supports the ACID database concepts (atomicity, consistency, isolation, and durability). We need merely close the transaction with a call to commit(). Had something gone awry during the transaction, we could have called abort(), and all operations that had occurred since the last commit() or open() would be rolled back.

Retrieving an object from this OO database is just as easy as storing it. We don't have to assemble an object's "pieces" from multiple tables; instead, we can pull it from the database with a single call. All we need is a query mechanism to identify the specific object we want.

db4o provides this mechanism via its QBE (query by example) API. QBE, as implemented by db4o, is an easy-to-understand query technique that uses a template object to define the query. We fill the template object's fields with those values we want the query to match. Fields that should not participate in the query are set to null or zero (depending on the datatype).

Therefore, if we wanted to fetch the Part object we had just stored into the database, we could use the code in Listing 3. The query in Listing 3 matches all Part objects whose name field is "Desktop Board D945GNT" (we presume there is only one). Matching objects are placed in the ObjectSet result. The ObjectSet class provides hasNext() and next() methods, which allow navigation-through-iteration on the set's contents.

The query fetched a Part object from the database. As defined, the Part object is relatively "simple" - that is, it contains only strings as member variables. The PartAssembly class, however, contains a collection, and that collection contains objects. One would expect that fetching a PartAssembly object - collection and all - would be more difficult.

Actually, it is only slightly more difficult. Although db4o lets us pull an entire object tree into memory, we might not want to. For example, we may want to fetch one or more PartAssembly objects from the database, without fetching the contained collection.

We can control how "deeply" db4o reaches into an object tree (when it retrieves a complex object from the database) by adjusting db4o's "activation depth." By default, the activation depth is set to 5, which means that retrieving a PartAssembly object would also retrieve the collection. (So, fetching a whole PartAssembly would use code that is virtually identical to the code in Listing 3.) To retrieve only the PartAssembly - without the components collection - we can set the global activation depth to 0, prior to opening the database as follows:

Db4o.configure().activationDepth(0);

Any database opened after the above call would have its activation depth set to 0.

Finally, deleting objects is as straightforward as fetching them. If we wanted to delete the Part object retrieved in the Listing 3, it requires a single line (placed where the ellipses are in the listing):

Database.delete(mb);

followed at some point, of course, with a commit().

Changes on the Fly
Suppose that a change in the application's requirements demands a change in an object's structure - perhaps something as simple as a new field. For example, suppose that you decided the Part class needed an alternateSupplier field.

With an RDBMS back end, you would have to modify one or more tables, plus make additions to the translation code, update the schema mapping file, and so on. However, with db4o, the alteration requires absolutely nothing beyond the change to the Part class definition (plus any added or modified methods you would have to write in any case):

public class Part {
    private string category;
    private string name;
    private string manufacturer;
    private string manufacturerPartNumber;
    private string alternateSupplier;
    . . .
}

Everything else remains the same. When db4o fetches a Part object from the database, it will find no content for alternateSupplier, and set that field to null. However, if we then assign a value to that field and return the object to the database, the effect will be to turn the "old" Part object into a "new" one (see Listing 4).

Thus, after the execution of the code in Listing 4, any time we fetch from the database the Part object associated with "Desktop Board D945GNT," it will have an alternateSupplier field of "Dougs Board Outlet."

OO All the Way
An object-oriented database makes a great deal of sense for a database application whose content is easily modeled in OO fashion. The mapping code required to move data between objects in the application and tables on the RDBMS is eliminated. Furthermore, such an application is simply easier to work with, because there is no conceptual boundary that must be crossed between the object model and the relational model.

The open-source database engine db4o made our illustration of these principles all the easier thanks to db4o's API, which is both easy to grasp and functionally powerful. In one sense, db4o hits a kind of "sweet spot" in that it is not overly complex, nor under-powered.

A complete .NET application that lets you create and manipulate a database identical to what we've described in this article is available from www.everylittlething.net/PartsAssembly/. The application was written using Visual Studio 2005, and includes everything you need to experiment with the Assembly database structure. We encourage you to explore the application, and discover the benefits of "OO all the way."

More Stories By Rick Grehan

Rick Grehan is a QA engineer at Compuware's NuMega Labs, where he has worked on Java and .NET projects. He is also a contributing editor for InfoWorld Magazine. His articles have appeared in Embedded Systems Programming, EDN, The Microprocessor Report, BYTE, Computer Design, and other journals. He is also the coauthor of three books on computer programming.

More Stories By Eric Falsken

Eric Falsken recently joined the db4o team as technical evangelist after spending a few years working on embedded medical devices as a db4o user. He has been a staunch supporter of Microsoft .NET (much to the chagrin of his open source?loving co-workers) and enjoys coming up with new ideas for elegantly usable software, and mentoring fellow students of software. You can read his blog at www.everylittlething.net/blog/.

Comments (2)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.