Welcome!

.NET Authors: Pat Romanski, Elizabeth White, ChandraShekar Dattatreya, Trevor Parsons, Peter Silva

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) View Comments

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.


Most Recent Comments
Eric Falsken 01/23/06 06:09:58 PM EST

Of course this is changing. The ODBMS systems of 15 years ago were much different. The new generation of object databases have been chronicled on an open industry website: http://www.odbms.org which notes the myriad advantages that modern ODBMS systems have over those of the prior generation. It's time for objects to take charge!

John Ingres 01/22/06 03:43:47 PM EST

To have fun an open source ODBMS is OK, but what are the real industry players in object databases today?
OO Databases still have not gained much momentum despite over 15 years of efforts. Do you really think it is changing? If so, why?

@ThingsExpo Stories
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
Cultural, regulatory, environmental, political and economic (CREPE) conditions over the past decade are creating cross-industry solution spaces that require processes and technologies from both the Internet of Things (IoT), and Data Management and Analytics (DMA). These solution spaces are evolving into Sensor Analytics Ecosystems (SAE) that represent significant new opportunities for organizations of all types. Public Utilities throughout the world, providing electricity, natural gas and water, are pursuing SmartGrid initiatives that represent one of the more mature examples of SAE. We have s...
The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it's a mix of architectural styles ...
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, discussed single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example t...
An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, discussed how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money!
The Internet of Things will put IT to its ultimate test by creating infinite new opportunities to digitize products and services, generate and analyze new data to improve customer satisfaction, and discover new ways to gain a competitive advantage across nearly every industry. In order to help corporate business units to capitalize on the rapidly evolving IoT opportunities, IT must stand up to a new set of challenges. In his session at @ThingsExpo, Jeff Kaplan, Managing Director of THINKstrategies, will examine why IT must finally fulfill its role in support of its SBUs or face a new round of...
One of the biggest challenges when developing connected devices is identifying user value and delivering it through successful user experiences. In his session at Internet of @ThingsExpo, Mike Kuniavsky, Principal Scientist, Innovation Services at PARC, described an IoT-specific approach to user experience design that combines approaches from interaction design, industrial design and service design to create experiences that go beyond simple connected gadgets to create lasting, multi-device experiences grounded in people's real needs and desires.
Enthusiasm for the Internet of Things has reached an all-time high. In 2013 alone, venture capitalists spent more than $1 billion dollars investing in the IoT space. With "smart" appliances and devices, IoT covers wearable smart devices, cloud services to hardware companies. Nest, a Google company, detects temperatures inside homes and automatically adjusts it by tracking its user's habit. These technologies are quickly developing and with it come challenges such as bridging infrastructure gaps, abiding by privacy concerns and making the concept a reality. These challenges can't be addressed w...
The Domain Name Service (DNS) is one of the most important components in networking infrastructure, enabling users and services to access applications by translating URLs (names) into IP addresses (numbers). Because every icon and URL and all embedded content on a website requires a DNS lookup loading complex sites necessitates hundreds of DNS queries. In addition, as more internet-enabled ‘Things' get connected, people will rely on DNS to name and find their fridges, toasters and toilets. According to a recent IDG Research Services Survey this rate of traffic will only grow. What's driving t...
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, examined three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics is e...
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
We are reaching the end of the beginning with WebRTC, and real systems using this technology have begun to appear. One challenge that faces every WebRTC deployment (in some form or another) is identity management. For example, if you have an existing service – possibly built on a variety of different PaaS/SaaS offerings – and you want to add real-time communications you are faced with a challenge relating to user management, authentication, authorization, and validation. Service providers will want to use their existing identities, but these will have credentials already that are (hopefully) i...
"Matrix is an ambitious open standard and implementation that's set up to break down the fragmentation problems that exist in IP messaging and VoIP communication," explained John Woolf, Technical Evangelist at Matrix, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at @ThingsExpo, Robin Raymond, Chief Architect at Hookflash, will walk through the shifting landscape of traditional telephone and voice services ...
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
The definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world.