Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you deal with polymorphism in a database?

Example

I have Person, SpecialPerson, and User. Person and SpecialPerson are just people - they don't have a user name or password on a site, but they are stored in a database for record keeping. User has all of the same data as Person and potentially SpecialPerson, along with a user name and password as they are registered with the site.


How would you address this problem? Would you have a Person table which stores all data common to a person and use a key to look up their data in SpecialPerson (if they are a special person) and User (if they are a user) and vice-versa?

like image 559
Thomas Owens Avatar asked Sep 05 '08 12:09

Thomas Owens


People also ask

What is database polymorphism?

Polymorphic association is a term used in discussions of Object-Relational Mapping with respect to the problem of representing in the relational database domain, a relationship from one class to multiple classes. In statically typed languages such as Java these multiple classes are subclasses of the same superclass.

What is polymorphism in SQL?

"polymorphism" means multiple shapes (multiple subprograms, same name). Overloading is static polymorphism because the COMPILER resolves which of the subprograms to execute (at compile time). Dynamic polymorphism means we have 2+ methods with the same name, but in different types in the same hierarchy.

What is inheritance in database?

Inheritance enables you to share attributes between objects such that a subclass inherits attributes from its parent class.


1 Answers

Take a look at Martin Fowler's Patterns of Enterprise Application Architecture:

  • Single Table Inheritance:

    When mapping to a relational database, we try to minimize the joins that can quickly mount up when processing an inheritance structure in multiple tables. Single Table Inheritance maps all fields of all classes of an inheritance structure into a single table.

  • Class Table Inheritance:

    You want database structures that map clearly to the objects and allow links anywhere in the inheritance structure. Class Table Inheritance supports this by using one database table per class in the inheritance structure.

  • Concrete Table Inheritance:

    Thinking of tables from an object instance point of view, a sensible route is to take each object in memory and map it to a single database row. This implies Concrete Table Inheritance, where there's a table for each concrete class in the inheritance hierarchy.

like image 148
Vitor Silva Avatar answered Sep 29 '22 18:09

Vitor Silva