简体   繁体   中英

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. 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. Are there better ways ? My Ids are of type Integer(4 bytes).

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. 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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