18

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • do you want to create your own method for generating unique id using timestamp? – Hemant Metalia Jan 30 '12 at 07:04
  • You can get one unique number and then can increment it by 1 every time while storing records into the DB. – Ved Jan 30 '12 at 07:09
  • 2
    @Sathish : Why not get the substring() according to your desired length and keep checking if the new one is equal to any previously assigned. UUID is the best way :-) Regards – nIcE cOw Jan 30 '12 at 07:10
  • @Hemant Metalia: I never mind to create a new method to generate codes by timestamp, but my question is, whether it will be unique? –  Jan 30 '12 at 07:24
  • @Gagandeep Bali: I feel substring() and checking that with the previous values (will have many id's) will take a long time.. will lead a performance issue !!! –  Jan 30 '12 at 07:25

6 Answers6

22

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

Slava Semushin
  • 14,904
  • 7
  • 53
  • 69
  • Hi.. Thanks a lot.. By using randomAlphanumeric(), we are getting codes as per the length we wish.. but unique?? –  Jan 30 '12 at 07:30
  • 1
    `randomAlphanumeric()` generates string with random characters and in most cases its unique (you also may try to run it in a loop and generate new unless its doesn't exists). – Slava Semushin Jan 30 '12 at 08:35
  • Thanks.. finally I have used RandomStringUtils.randomAlphanumeric(10) to generate the code and check that code existence in database. If not exists, I am using it as my unique code.. –  Feb 07 '12 at 06:06
7

Do you have any specific limitation you need to take into account? Such as cross-application uniqueness? Because otherwise, MySQL is quite capable of generating IDs by itself, all you need to do is define an autoincrement column and not specify it at insert time (meaning, inserting a NULL value for it) - that will make MySQL fill it with the next available ID, unique and requiring no work from you.

It won't be an alphanumerical string (which I'm not sure if you specified as a requirement or restriction), but if all you require is uniqueness, it's more than enough. 8 - 10 alphanumeric characters aren't enough to guarantee uniqueness in a randomly-generated string, so you'd have to perform an insert check on the database.

Naltharial
  • 2,132
  • 14
  • 21
5

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

Databases are designed to be able to generate unique IDs where needed. I doubt anything you (or I) could code would be a 'better' variant of that.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Thank you. If so, Can you give me some examples on how to do generate unique IDs for MySQL databases. –  Jan 30 '12 at 07:29
  • 2
    Try [any of these](http://www.google.com.au/search?q=generate+unique+IDs+for+MySQL&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a). I don't use DBs on a day to day basis, and have never used MySQL. – Andrew Thompson Jan 30 '12 at 07:34
1

I have written a simple service which can generate semi-unique non-sequential 64 bit long numbers. It can be deployed on multiple machines for redundancy and scalability. It uses ZeroMQ for messaging. For more information on how it works look at github page: zUID

Majid Azimi
  • 5,575
  • 13
  • 64
  • 113
0

Take look at: UIDGenerator.java

You can customize it (unique to process only, or world), it is easy to use and fast:

    private static final UIDGenerator SCA_GEN = new UIDGenerator(new ScalableSequence(0, 100));
.......
    SCA_GEN.next();

You can change the implementation to reduce the size of the ID (and add other tradeoffs)

see my benchmarking results at:

http://zoltran.com/roller/zoltran/entry/generating_a_unique_id

or run them yourself.

user2179737
  • 493
  • 3
  • 6
  • In case I use UID Generator will it be unique in multi clustered java application , Will that id be unique even if server is restarted?? – Shweta Gulati Oct 18 '16 at 10:32
0

The question if id generation part be done in database or java end: This question has to be answered by you depending on requirements of your application:

1) One way is to go by System.currenTimeMillis() . But if your applicaation will work in multi clustered env, then you may end up with duplicate values.

http://www2.sys-con.com/itsg/virtualcd/java/archives/0512/Westra/index.html

2) Another way is to use UUID Generator .It will help you in case you have different databases that need to be merged. Using this mehtod you don't have to worry about duplication of id when merging databases.

https://marketplace.informatica.com/solutions/mapping_uuid_using_java

There may be other factors you may want to consider. As per your question UUID method will go.

Shweta Gulati
  • 566
  • 1
  • 7
  • 17