Tuesday, April 15, 2014

Different Ways to Generate Unique ID

We had a requirement to generate 32 character alpha numeric unique IDs. Many options came up - here is the summary of options we considered.

Java UUID:

With Java 1.5 UUID class was introduced. This would generate universally unique identifier (UUID). A UUID represents a 128-bit value. randomUUID() method in UUID class will generate 128-bit universally unique value every time the method is called. This is hash-based values separated by dashes. Java API available here: http://docs.oracle.com/javase/6/docs/api/index.html?java/util/UUID.html

Database Hash:

If system design and architecture allows the unique ID generation on database side, then database hash can be used to create unique IDs.

Composite Key in Database:

If there is a way to combine various non unique keys to form a primary key on database side, this might work as an option as well.

Apache Commons:

randomAlphanumeric(int) in RandomStringUtils class takes length as an arguments and generates alpha numeric values. API documentation is here: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html

Conclusion:

What worked for us in first phase of implementation was an approach where we used the system provided columns to generate a composite key.

Later the requirement changed to use alphanumeric values at which point in time we used RandomStringUtils provided by Apache Commons. However, it came with an overhead to check the generated ID against the database. However, this didn't have impact on performance given the benchmarks. 

No comments:

Post a Comment