How do you deal with polymorphism in a database?

后端 未结 13 1190
小蘑菇
小蘑菇 2020-11-28 02:11

Example

I have Person, SpecialPerson, and User. Person and SpecialPerson are just people - they don\

13条回答
  •  悲哀的现实
    2020-11-28 02:52

    There are generally three ways of mapping object inheritance to database tables.

    You can make one big table with all the fields from all the objects with a special field for the type. This is fast but wastes space, although modern databases save space by not storing empty fields. And if you're only looking for all users in the table, with every type of person in it things can get slow. Not all or-mappers support this.

    You can make different tables for all the different child classes with all of the tables containing the base-class fields. This is ok from a performance perspective. But not from a maintenance perspective. Every time your base-class changes all the tables change.

    You can also make a table per class like you suggested. This way you need joins to get all the data. So it's less performant. I think it's the cleanest solution.

    What you want to use depends of course on your situation. None of the solutions is perfect so you have to weigh the pros and cons.

提交回复
热议问题