Classes to Tables

--Originally published at Computer Systems Engineering

When you  already have the objects that you want properly designed its time to put them on a relational database. The first thing you need to look at are the data attributes of each class that has to be mapped to zero or more columns depending on your design.

 

This is an example of how you translate a UML diagram into a data model for a relational database. Overall, the thing you do is put each attribute with its data type and indicate which one will be your primary key. For the attributes that are connected to other classes as well (meaning that they belong to more than one table) you indicate that they are foreign keys. While doing all this process we ignore the methids of the classes, that will come later in the developement of the solution.

A very important aspect you need to take into account while mappingis also inheritance. It can be approached with different techniques according to your program’s structure:

  • Map the entire class hierarchy to a single table: just like the name suggests, it consists in making each attribute of the class into a data object in just one table.
  • Map each class to its own table: with this approach a table is created for each concrete class, each table including both the attributes implemented by the class and its inherited attributes, create one table per class, with one column per business attributes and any necessary identification information.
  • Map the classes into a generic table structure: with this technique you use a generic (meta-data) driven approach.

In the image we can see how different the physical data model can be according to  which method you use to map it. For example, in the pic at top they used a ‘mao entire class hierarchy to a single table which is faster but less clear and messy. In the middle we have the ‘Map each class to its own table’ approach, and lastly we have the ‘Map the classes into a generic table structure’ technique.

 

References:

http://www.agiledata.org/essays/mappingObjects.html