Click here to close now.

Welcome!

.NET Authors: Greg O'Connor, Jayaram Krishnaswamy, Adine Deford, Peter Silva, Pat Romanski

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
SYS-CON Events announced today that Cisco, the worldwide leader in IT that transforms how people connect, communicate and collaborate, has been named “Gold Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Cisco makes amazing things happen by connecting the unconnected. Cisco has shaped the future of the Internet by becoming the worldwide leader in transforming how people connect, communicate and collaborate. Cisco and our partners are building the platform for the Internet of Everything by connecting the...
Wearable technology was dominant at this year’s International Consumer Electronics Show (CES) , and MWC was no exception to this trend. New versions of favorites, such as the Samsung Gear (three new products were released: the Gear 2, the Gear 2 Neo and the Gear Fit), shared the limelight with new wearables like Pebble Time Steel (the new premium version of the company’s previously released smartwatch) and the LG Watch Urbane. The most dramatic difference at MWC was an emphasis on presenting wearables as fashion accessories and moving away from the original clunky technology associated with t...
Temasys has announced senior management additions to its team. Joining are David Holloway as Vice President of Commercial and Nadine Yap as Vice President of Product. Over the past 12 months Temasys has doubled in size as it adds new customers and expands the development of its Skylink platform. Skylink leads the charge to move WebRTC, traditionally seen as a desktop, browser based technology, to become a ubiquitous web communications technology on web and mobile, as well as Internet of Things compatible devices.
SYS-CON Events announced today that robomq.io will exhibit at SYS-CON's @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. robomq.io is an interoperable and composable platform that connects any device to any application. It helps systems integrators and the solution providers build new and innovative products and service for industries requiring monitoring or intelligence from devices and sensors.
Docker is an excellent platform for organizations interested in running microservices. It offers portability and consistency between development and production environments, quick provisioning times, and a simple way to isolate services. In his session at DevOps Summit at 16th Cloud Expo, Shannon Williams, co-founder of Rancher Labs, will walk through these and other benefits of using Docker to run microservices, and provide an overview of RancherOS, a minimalist distribution of Linux designed expressly to run Docker. He will also discuss Rancher, an orchestration and service discovery platf...
SYS-CON Events announced today that Akana, formerly SOA Software, has been named “Bronze Sponsor” of SYS-CON's 16th International Cloud Expo® New York, which will take place June 9-11, 2015, at the Javits Center in New York City, NY. Akana’s comprehensive suite of API Management, API Security, Integrated SOA Governance, and Cloud Integration solutions helps businesses accelerate digital transformation by securely extending their reach across multiple channels – mobile, cloud and Internet of Things. Akana enables enterprises to share data as APIs, connect and integrate applications, drive part...
SYS-CON Events announced today that Vitria Technology, Inc. will exhibit at SYS-CON’s @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Vitria will showcase the company’s new IoT Analytics Platform through live demonstrations at booth #330. Vitria’s IoT Analytics Platform, fully integrated and powered by an operational intelligence engine, enables customers to rapidly build and operationalize advanced analytics to deliver timely business outcomes for use cases across the industrial, enterprise, and consumer segments.
SYS-CON Events announced today that Solgenia will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY, and the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Solgenia is the global market leader in Cloud Collaboration and Cloud Infrastructure software solutions. Designed to “Bridge the Gap” between Personal and Professional Social, Mobile and Cloud user experiences, our solutions help large and medium-sized organizations dr...
SYS-CON Events announced today that Liaison Technologies, a leading provider of data management and integration cloud services and solutions, has been named "Silver Sponsor" of SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York, NY. Liaison Technologies is a recognized market leader in providing cloud-enabled data integration and data management solutions to break down complex information barriers, enabling enterprises to make smarter decisions, faster.
Cloud is not a commodity. And no matter what you call it, computing doesn’t come out of the sky. It comes from physical hardware inside brick and mortar facilities connected by hundreds of miles of networking cable. And no two clouds are built the same way. SoftLayer gives you the highest performing cloud infrastructure available. One platform that takes data centers around the world that are full of the widest range of cloud computing options, and then integrates and automates everything. Join SoftLayer on June 9 at 16th Cloud Expo to learn about IBM Cloud's SoftLayer platform, explore se...
The WebRTC Summit 2014 New York, to be held June 9-11, 2015, at the Javits Center in New York, NY, announces that its Call for Papers is open. Topics include all aspects of improving IT delivery by eliminating waste through automated business models leveraging cloud technologies. WebRTC Summit is co-located with 16th International Cloud Expo, @ThingsExpo, Big Data Expo, and DevOps Summit.
@ThingsExpo has been named the Top 5 Most Influential M2M Brand by Onalytica in the ‘Machine to Machine: Top 100 Influencers and Brands.' Onalytica analyzed the online debate on M2M by looking at over 85,000 tweets to provide the most influential individuals and brands that drive the discussion. According to Onalytica the "analysis showed a very engaged community with a lot of interactive tweets. The M2M discussion seems to be more fragmented and driven by some of the major brands present in the M2M space. This really allows some room for influential individuals to create more high value inter...
The world's leading Cloud event, Cloud Expo has launched Microservices Journal on the SYS-CON.com portal, featuring over 19,000 original articles, news stories, features, and blog entries. DevOps Journal is focused on this critical enterprise IT topic in the world of cloud computing. Microservices Journal offers top articles, news stories, and blog posts from the world's well-known experts and guarantees better exposure for its authors than any other publication. Follow new article posts on Twitter at @MicroservicesE
SYS-CON Events announced today the IoT Bootcamp – Jumpstart Your IoT Strategy, being held June 9–10, 2015, in conjunction with 16th Cloud Expo and Internet of @ThingsExpo at the Javits Center in New York City. This is your chance to jumpstart your IoT strategy. Combined with real-world scenarios and use cases, the IoT Bootcamp is not just based on presentations but includes hands-on demos and walkthroughs. We will introduce you to a variety of Do-It-Yourself IoT platforms including Arduino, Raspberry Pi, BeagleBone, Spark and Intel Edison. You will also get an overview of cloud technologies s...
SYS-CON Events announced today that SafeLogic has been named “Bag Sponsor” of SYS-CON's 16th International Cloud Expo® New York, which will take place June 9-11, 2015, at the Javits Center in New York City, NY. SafeLogic provides security products for applications in mobile and server/appliance environments. SafeLogic’s flagship product CryptoComply is a FIPS 140-2 validated cryptographic engine designed to secure data on servers, workstations, appliances, mobile devices, and in the Cloud.
Containers and microservices have become topics of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 16th Cloud Expo at the Javits Center in New York June 9-11 will find fresh new content in a new track called PaaS | Containers & Microservices Containers are not being considered for the first time by the cloud community, but a current era of re-consideration has pushed them to the top of the cloud agenda. With the launch of Docker's initial release in March of 2013, interest was revved up several notches. Then late last...
SOA Software has changed its name to Akana. With roots in Web Services and SOA Governance, Akana has established itself as a leader in API Management and is expanding into cloud integration as an alternative to the traditional heavyweight enterprise service bus (ESB). The company recently announced that it achieved more than 90% year-over-year growth. As Akana, the company now addresses the evolution and diversification of SOA, unifying security, management, and DevOps across SOA, APIs, microservices, and more.
After making a doctor’s appointment via your mobile device, you receive a calendar invite. The day of your appointment, you get a reminder with the doctor’s location and contact information. As you enter the doctor’s exam room, the medical team is equipped with the latest tablet containing your medical history – he or she makes real time updates to your medical file. At the end of your visit, you receive an electronic prescription to your preferred pharmacy and can schedule your next appointment.
The Open Compute Project is a collective effort by Facebook and a number of players in the datacenter industry to bring lessons learned from the social media giant's giant IT deployment to the rest of the world. Datacenters account for 3% of global electricity consumption – about the same as all of Switzerland or the Czech Republic -- according to people I met at the recent Open Compute Summit in San Jose. With increasing mobility at the edge of the cloud and vast new dataflows being predicted with the growth of the Internet of Things (and The Coming Age of Many Zettabytes) in the near...
GENBAND has announced that SageNet is leveraging the Nuvia platform to deliver Unified Communications as a Service (UCaaS) to its large base of retail and enterprise customers. Nuvia’s cloud-based solution provides SageNet’s customers with a full suite of business communications and collaboration tools. Two large national SageNet retail customers have recently signed up to deploy the Nuvia platform and the company will continue to sell the service to new and existing customers. Nuvia’s capabilities include HD voice, video, multimedia messaging, mobility, conferencing, Web collaboration, deskt...