Click here to close now.

Welcome!

Microsoft Cloud Authors: Elizabeth White, Liz McMillan, Pat Romanski, Jaynesh Shah, Carmen Gonzalez

Related Topics: Microsoft Cloud

Microsoft Cloud: 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 BMC 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. BMC delivers software solutions that help IT transform digital enterprises for the ultimate competitive business advantage. BMC has worked with thousands of leading companies to create and deliver powerful IT management services. From mainframe to cloud to mobile, BMC pairs high-speed digital innovation with robust IT industrialization – allowing customers to provide amazing user experiences with optimized IT per...
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...
SYS-CON Events announced today that MetraTech, now part of Ericsson, 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. Ericsson is the driving force behind the Networked Society- a world leader in communications infrastructure, software and services. Some 40% of the world’s mobile traffic runs through networks Ericsson has supplied, serving more than 2.5 billion subscribers.
The world is at a tipping point where the technology, the device and global adoption are converging to such a point that we will see an explosion of a world where smartphone devices not only allow us to talk to each other, but allow for communication between everything – serving as a central hub from which we control our world – MediaTek is at the heart of both driving this and allowing the markets to drive this reality forward themselves. The next wave of consumer gadgets is here – smart, connected, and small. If your ambitions are big, so are ours. In his session at @ThingsExpo, Jack Hu, D...
The 4th International Internet of @ThingsExpo, co-located with the 17th International Cloud Expo - to be held November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA - announces that its Call for Papers is open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
SYS-CON Events announced today that DragonGlass, an enterprise search platform, 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. After eleven years of designing and building custom applications, OpenCrowd has launched DragonGlass, a cloud-based platform that enables the development of search-based applications. These are a new breed of applications that utilize a search index as their backbone for data retrieval. They can easily adapt to new data sets and provide access to both structured and unstruc...
We’re entering a new era of computing technology that many are calling the Internet of Things (IoT). Machine to machine, machine to infrastructure, machine to environment, the Internet of Everything, the Internet of Intelligent Things, intelligent systems – call it what you want, but it’s happening, and its potential is huge. IoT is comprised of smart machines interacting and communicating with other machines, objects, environments and infrastructures. As a result, huge volumes of data are being generated, and that data is being processed into useful actions that can “command and control” thi...
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at @ThingsExpo, Andrew Bolwell, Director of Innovation for HP's Printing and Personal Systems Group, discussed how key attributes of mobile technology – touch input, sensors, social, and ...
All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo, June 9-11, 2015, at the Javits Center in New York City. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be
The Internet of Things is not only adding billions of sensors and billions of terabytes to the Internet. It is also forcing a fundamental change in the way we envision Information Technology. For the first time, more data is being created by devices at the edge of the Internet rather than from centralized systems. What does this mean for today's IT professional? In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists will addresses this very serious issue of profound change in the industry.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, discussed how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.
Buzzword alert: Microservices and IoT at a DevOps conference? What could possibly go wrong? In this Power Panel at DevOps Summit, moderated by Jason Bloomberg, the leading expert on architecting agility for the enterprise and president of Intellyx, panelists will peel away the buzz and discuss the important architectural principles behind implementing IoT solutions for the enterprise. As remote IoT devices and sensors become increasingly intelligent, they become part of our distributed cloud environment, and we must architect and code accordingly. At the very least, you'll have no problem fil...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
"People are a lot more knowledgeable about APIs now. There are two types of people who work with APIs - IT people who want to use APIs for something internal and the product managers who want to do something outside APIs for people to connect to them," explained Roberto Medrano, Executive Vice President at SOA Software, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
In their session at @ThingsExpo, Shyam Varan Nath, Principal Architect at GE, and Ibrahim Gokcen, who leads GE's advanced IoT analytics, focused on the Internet of Things / Industrial Internet and how to make it operational for business end-users. Learn about the challenges posed by machine and sensor data and how to marry it with enterprise data. They also discussed the tips and tricks to provide the Industrial Internet as an end-user consumable service using Big Data Analytics and Industrial Cloud.
Building low-cost wearable devices can enhance the quality of our lives. In his session at Internet of @ThingsExpo, Sai Yamanoor, Embedded Software Engineer at Altschool, provided an example of putting together a small keychain within a $50 budget that educates the user about the air quality in their surroundings. He also provided examples such as building a wearable device that provides transit or recreational information. He then reviewed the resources available to build wearable devices at home including open source hardware, the raw materials required and the options available to power s...
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 ...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
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...
Collecting data in the field and configuring multitudes of unique devices is a time-consuming, labor-intensive process that can stretch IT resources. Horan & Bird [H&B], Australia’s fifth-largest Solar Panel Installer, wanted to automate sensor data collection and monitoring from its solar panels and integrate the data with its business and marketing systems. After data was collected and structured, two major areas needed to be addressed: improving developer workflows and extending access to a business application to multiple users (multi-tenancy). Docker, a container technology, was used to ...