简体   繁体   English

将ID与扩展名并置,以使与一个实体相关的多个行保持在单个列族中

[英]Concatenating ids with extension to keep multiple rows related to an entity in a single Column Family

I am concatenating two Integer ids through bitwise operations(as described below) to create a single primary key of type long. 我通过按位操作(如下所述)连接两个Integer ID,以创建一个long型的主键。 I wanted to know if this is a good practice. 我想知道这是否是一个好习惯。 This would help me in keeping multiple rows of an entity in a single column family by appending different extensions to the entityId. 通过将不同的扩展名附加到entityId,这将有助于我将一个实体的多个行保留在一个列族中。 Are there better ways ? 有更好的方法吗? My Ids are of type Integer(4 bytes). 我的ID的类型为Integer(4个字节)。

public static final long makeCompositeKey(int entityId, int extension){
    return (long)entityId << 32 | extension;
}

Most databases come with a built-in way to create IDs automatically, and your app doesn't need to care about it. 大多数数据库都具有内置的自动创建ID的方式,您的应用无需关心它。 I'm most familiar with Postgres, where I create a sequence for each table and use that for the @Id column, but I know that Oracle and MSSQL have their own way of accomplishing the same thing. 我对Postgres最熟悉,我在其中为每个表创建一个序列并将其用于@Id列,但是我知道Oracle和MSSQL具有完成同一件事的自己的方式。

In general, however, each column in your database should store a single piece of information. 但是,通常,数据库中的每一列都应存储一条信息。 Taking two pieces of info and concatenating them together as you're suggesting goes against "proper" database design according to "book learning." 根据您的建议,获取两条信息并将它们连接在一起会违反“根据书本知识”进行的“正确”数据库设计。 By which I mean: you should only do it if you have a very, very good reason for doing so (and even then, you should think two or three times about it before actually doing it.) If you don't have a good reason for doing it, then don't do it. 我的意思是:只有在您有非常非常好的理由这样做时,您才应该这样做(即使那样,您在进行实际操作之前也应该考虑两三遍。)这样做的原因,那就不要这样做。

This is not a good design. 这不是一个好的设计。 It should be two different columns having composite constraint. 它应该是具有复合约束的两个不同的列。 You can have a another generated Unique ID for as a primary key. 您可以使用另一个生成的唯一ID作为主键。

Aside from the primary key, You can also create a composite index on two columns to speed up the queries if most queries will filter based on these two values. 除了主键之外,如果大多数查询将基于这两个值进行过滤,则还可以在两列上创建复合索引以加快查询速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM