Generate unique ID

user915303 picture user915303 · Jan 30, 2012 · Viewed 26.9k times · Source

I need to generate unique ID's for my application. When I used (UUID.randomUUID()).toString(), I am getting a code (thinking this will be unique), which is very lengthy.

I am not sure how unique it will be, when we generate codes with the help of Java Timestamp or randomstring.

I need to generate unique codes which is only of 8-10 characters in length (alpha-numeric). How to get so? I am using MySQL database.

Is generating unique code on database side is the best way or can we generate such short (but unique) codes in Java?

Any suggestions with example code will be very helpful.

Answer

Slava Semushin picture Slava Semushin · Jan 30, 2012

I use RandomStringUtils.randomAlphanumeric() method from commons-lang to achieve this:

import org.apache.commons.lang.RandomStringUtils;

public static final int ID_LENGTH = 10;

public String generateUniqueId() {
    return RandomStringUtils.randomAlphanumeric(ID_LENGTH);
}

If you using Maven, ensure that you have added commons-lang to project's dependencies:

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

Is generating unique code on database side is the best way or can we generate such short (but unique) codes in java?

It's up to you and your project. Is id-generation part of business logic? If yes and all logic written on Java, so write it on Java. If all or some part of logic delegated to database, so generate id there (but in this case you will have strong dependency to particular database).