为什么复合键在hibernate不鼓励? [英] Why are composite keys discouraged in hibernate?
问题描述
这是来自 Hibernate官方教程 :
有一个替代
< composite-id>
到具有复合键的遗留数据。
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个参数,而不只是一个。
- 它们效率低下。
- 它们会导致错误:开发人员不可避免地不正确地实现主键类的equals和hashCode方法,而不是简单地对整数进行散列。或者它们使它变得可变,并且一旦存储在HashSet或HashMap中就修改它们的值
- 它们污染了模式。如果另一个表需要引用这个3列表,它将需要有一个3列,而不是只有一个作为外键。现在假设你遵循相同的设计,并使这个新表的主键的这个3列外键部分,你会很快有一个4列的主键,然后在下表中的5列PK等。
- they're cumbersome to use. Each time you need to reference an object (or row), for eexample in your web application, you need to pass 3 parameters instead of just one.
- they're inefficient. Instead of simply hashing an integer, the database needs to hash a composite of 3 columns.
- they lead to bugs: developers inevitably implement the equals and hashCode methods of the primary key class incorrectly. Or they make it mutable, and modify their value once stored in a HashSet or HashMap
- they pollute the schema. If another table needs to reference this 3-column table, it will need to have a 3 columns instead of just one as a foreign key. Now suppose you follow the same design and make this 3-column foreign key part of the primary key of this new table, you'll quickly have a 4-column primary key, and then a 5-column PK in the next table, etc. etc., leading to duplication of data, and a dirty schema.
另一种方法是使用单列,生成的主键,除了其他三列。如果要使三列的元组唯一,则使用唯一约束。
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.
这篇关于为什么复合键在hibernate不鼓励?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!