for example
class veiculo
class carro extends veiculo
class moto extends veiculo
What is the best way to represent these hierarchies in the relational database, one table for each type? same vehicle being an abstract class?
for example
class veiculo
class carro extends veiculo
class moto extends veiculo
What is the best way to represent these hierarchies in the relational database, one table for each type? same vehicle being an abstract class?
There are several ways to map the inheritance relationship in the bank. The best strategy will depend on the situation (types of queries that will be carried out against the data, number of common fields vs. specific fields, size of hierarchy, amount of data, etc.)
Each table will contain not only the data of the child class but also the data of the parent class. This allows "independent" car-motorcycle queries to be simpler and faster. However queries searching for data from more than one entity require the use of queries with union all
(which is problematic for a number of reasons).
A single table will contain all data for all entities. To differentiate between cars and motorbikes we use a discriminating column. This allows "generic" (i.e., all vehicles) queries to be simpler quick. It is especially appropriate when there are few specific car and motorcycle attributes (thus avoiding a large amount of null values).
This template is appropriate when normalization is essential and the child tables have many columns. In addition, this strategy is especially interesting for working with multiple inheritance (one entity can be of several types in the hierarchy simultaneously). The weakness of this modeling is that queries require join
, which makes code complex and brings performance problems as the amount of data and the depth of the hierarchy grows.
Nothing prevents you from modeling part of your hierarchy according to one strategy and part to another. For example, you can have a main vehicle table with data common to all vehicles (speed, size, weight, etc.), but have unique tables for each type of vehicle (land vehicles, aquatic, flying, etc.) p>
All strategies have their advantages and disadvantages; OO and relational representations are sufficiently different for several mapping problems to exist (see Object-relational impedance mismatch ). If your problem can not be adequately addressed by any of the strategies, there are also solutions with object-oriented database , (see Schemaless Data Structures > Martin Fowler), indexes, etc. Each one with its respective strengths and weaknesses.