简体   繁体   中英

Java String hashcode as Mysql ID

The scenario is something like this description.

I've the typical mysql table for the users storage, currently, the user ID is one integer set as autoincrement. Very much of the API rest interfaces works with the user alias (that's unique) to find the user, then, I'm thinking implement the user ID with the alias.hashcode() (that's one integer) to find diretly for ID every times.

Is a good idea implement Mysql ID with one java String hashcode?. Would enhance the performance?

Don't use String hashCode as your ID, since it's not unique. Two different Strings may have the same hashCode. I'm assuming your ID should be unique.

I don't think it's a great idea. The pigeon hole principle states (from Wikipedia) if n items are put into m containers, with n > m , then at least one container must contain more than one item . Basically, your solution cannot handle collisions and collisions are very possible with hashing.

Just add an index on the alias column, and query the db by alias directly. There are two problems with using alias hash code or other derivatives as an id. First, as others pointed out, hash codes are not be unique (this can be almost solved by changing the id type to string, and using a digest instead of the hash. Collisions with digests, while still possible, are extremely unlikely). Second, if the user changes his alias, the value will get out of sync with the id. If functionality of your application is such, that this situation is either impossible or unimportant, then you don't really need an id at all, and can identify users by alias directly.

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