为什么不鼓励在休眠中使用复合键? [英] Why are composite keys discouraged in hibernate?
问题描述
本文来自 Hibernate 官方教程:
有一个替代的
声明,它允许使用复合键访问遗留数据.强烈建议不要将其用于其他任何用途.
There is an alternative
<composite-id>
declaration that allows access to legacy data with composite keys. Its use is strongly discouraged for anything else.
为什么不鼓励使用复合键?我正在考虑使用一个 3 列表,其中所有列都是外键,并共同形成一个主键,这在我的模型中是有意义的关系.我不明白为什么这是一个坏主意,特别是我将对它们使用索引.
Why are composite keys discouraged? I am considering using a 3-column table where all of the columns are foreign keys and together form a primary key that is a meaningful relationship in my model. I don't see why this is a bad idea, espicially that I will be using an index on them.
有什么选择?创建一个额外的自动生成的列并将其用作主键?我仍然需要查询我的 3 列!?
What's the alternative? Create an additional automatically generated column and use it as a primary key? I still need to query my 3 columns anyways!?
简而言之,为什么这个说法是正确的?什么是更好的选择?
In short, why is this statement true? and what's the better alternative?
推荐答案
他们出于以下几个原因不鼓励他们:
They discourage them for several reasons:
- 它们使用起来很麻烦.每次您需要引用一个对象(或行)时,例如在您的 Web 应用程序中,您都需要传递 3 个参数而不是一个.
- 它们效率低下.数据库需要对 3 列的组合进行散列,而不是简单地散列一个整数.
- 它们会导致错误:开发人员不可避免地会错误地实现主键类的 equals 和 hashCode 方法.或者他们使它可变,并修改它们存储在 HashSet 或 HashMap 中的值
- 它们会污染架构.如果另一个表需要引用这个 3 列表,它将需要有 3 列而不是只有一个作为外键.现在假设您遵循相同的设计并将这个 3 列的外键部分作为这个新表的主键,您将很快拥有一个 4 列的主键,然后在下一个表中拥有一个 5 列的 PK,等等. 等,导致数据重复和脏模式.
替代方法是除了其他三列之外,还有一个自动生成的单列主键.如果要使三列的元组唯一,请使用唯一约束.
The alternative is to have a single-column, auto-generated primary key, in addition to the other three columns. If you want to make the tuple of three columns unique, then use a unique constraint.
这篇关于为什么不鼓励在休眠中使用复合键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!