Welcome!

.NET Authors: Pat Romanski, Trevor Parsons, Peter Silva, Esmeralda Swartz, Yeshim Deniz

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
Technology is enabling a new approach to collecting and using data. This approach, commonly referred to as the "Internet of Things" (IoT), enables businesses to use real-time data from all sorts of things including machines, devices and sensors to make better decisions, improve customer service, and lower the risk in the creation of new revenue opportunities. In his General Session at Internet of @ThingsExpo, Dave Wagstaff, Vice President and Chief Architect at BSQUARE Corporation, discuss the real benefits to focus on, how to understand the requirements of a successful solution, the flow of ...
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

Focused on this fast-growing market’s needs, Vitesse Semiconductor Corporation (Nasdaq: VTSS), a leading provider of IC solutions to advance "Ethernet Everywhere" in Carrier, Enterprise and Internet of Things (IoT) networks, introduced its IStaX™ software (VSC6815SDK), a robust protocol stack to simplify deployment and management of Industrial-IoT network applications such as Industrial Ethernet switching, surveillance, video distribution, LCD signage, intelligent sensors, and metering equipment. Leveraging technologies proven in the Carrier and Enterprise markets, IStaX is designed to work ac...
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
C-Labs LLC, a leading provider of remote and mobile access for the Internet of Things (IoT), announced the appointment of John Traynor to the position of chief operating officer. Previously a strategic advisor to the firm, Mr. Traynor will now oversee sales, marketing, finance, and operations. Mr. Traynor is based out of the C-Labs office in Redmond, Washington. He reports to Chris Muench, Chief Executive Officer. Mr. Traynor brings valuable business leadership and technology industry expertise to C-Labs. With over 30 years' experience in the high-tech sector, John Traynor has held numerous...
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 3rd International @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 it is now accepting Keynote Proposals. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. 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.
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...
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.
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, 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. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
SYS-CON Events announced today that IDenticard 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. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
IoT is still a vague buzzword for many people. In his session at @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, discussed the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. He also discussed how IoT is perceived by investors and how venture capitalist access this space. Other topics discussed were barriers to success, what is new, what is old, and what the future may hold. Mike Kavis is Vice President & Principal Cloud Architect at Cloud Technology Pa...
The Industrial Revolution in the 18th to 19th centuries was a period during which predominantly rural societies in Europe and America became industrial and urban. Advances in steam technology, transportation, mass production and the telegraph collectively transformed industry and society. Today, the Internet of Things (IoT) has the potential to once again transform industry and society just as the Industrial Revolution did. Analyst firm IDC forecasts that the IoT market will grow to $8.9 trillion by 2020 with anywhere between 30 to 50 billion connected autonomous things, making the potential g...
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. The next @ThingsExpo will take place November 4-6, 2014, at the Santa Clara Convention Center, in Santa Clara, California. Since its launch in 2008, Cloud Expo TV commercials have been aired and CNBC, Fox News Network, and Bloomberg TV. Please enjoy our 2014 commercial.
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
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.
Located in booth #314, the Bsquare team will present DataV demos and discuss how DataV will help customers put their data to work to improve business outcomes. DataV is unlocking new initiatives across a wide landscape of customers in industries such as industrial manufacturing, transportation, retail and mobile. The solution is designed to complement a new project start or help to enrich an existing machine investment.
The Physical Web incorporates beacons that can be put in any small retail store, for example, so that every store now has "an app" for its customers. In this Birds-of-a-Feather session at Internet of @ThingsExpo, Scott Jenson, Product Designer at Google, will discuss the Physical Web and how it is an open standard so any device can broadcast a URL wirelessly, so any phone/tablet/watch nearby can see, and rank those devices. When the user taps on one, they just go to that web page. It's really that simple. It's about thinking small, enabling micro-information (what is in my prescription bottle...
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.