你如何处理数据库中的多态性? [英] How do you deal with polymorphism in a database?

查看:38
本文介绍了你如何处理数据库中的多态性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例

我有 PersonSpecialPersonUser.PersonSpecialPerson 只是人——他们在网站上没有用户名或密码,但他们存储在数据库中以供记录.用户拥有与 Person 和潜在的 SpecialPerson 相同的所有数据,以及他们在网站上注册时的用户名和密码.

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.

你会如何解决这个问题?您是否有一个 Person 表来存储一个人共有的所有数据,并使用一个键在 SpecialPerson(如果他们是一个特殊的人)和 User(如果他们是用户),反之亦然?

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?

推荐答案

对象继承映射到数据库表一般有三种方式.

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.

这篇关于你如何处理数据库中的多态性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆