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

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

问题描述

示例

我有 SpecialPerson ,和用户 Person SpecialPerson 只是人 - 他们在网站上没有用户名或密码,但他们是存储在数据库中用于记录保存。用户具有与 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 (如果他们是一个特殊的人)和用户(如果他们是用户),反之亦然?

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.

您可以使用所有对象的所有字段创建一个大表,其中包含该类型的特殊字段。这是快速但浪费空间,虽然现代数据库通过不存储空字段来节省空间。如果你只是在寻找表中的所有用户,每个类型的人都可以慢慢的。不是所有的or-mappers都支持这一点。

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天全站免登陆