2

I am using UUID Random number as a primary key of Object when i save object in Database. So this generated UUID number should be unique. This way i got random number.


final String UUIDUserToken = UUID.randomUUID().toString()  

Can this generated number unique for any generated number?

Give me idea.

jmj
  • 237,923
  • 42
  • 401
  • 438
Pradeep Gamage
  • 585
  • 4
  • 8
  • 21

2 Answers2

4

It may repeat (with very little possibility) ,

Update:

try{
  //try inserting
}catch(){
  //SQL constraint fails
  // regenerate new UUID
  //check in DB before inserting
  //insert now, if its unique, else regenerate
}
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 4
    The probability of getting an repeated UUID is so small, just handle the error when you get it (regenerate the UUID). no need to check the DB every time – Aviram Segal Aug 13 '12 at 08:42
  • 1
    Agreed - just let a database constraint catch it if it ever happens. – Arnout Engelen Aug 13 '12 at 08:42
  • @AviramSegal How will you know its repeated if you don't check the database? Are you saying you should just assume it won't repeat and handle it if it has? – Peter Lawrey Aug 13 '12 at 08:43
  • 2
    @PeterLawrey try to insert, if you get an exception because the primary key is not unique make a new one, I see Jigar edited his answer to this method – Aviram Segal Aug 13 '12 at 12:32
0

The generated ID is unique world-wide by definition. BTW, why are you generating primary key in java code? Database knows to do this job very well. Just define the field as AUTO INCREMENT.

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • 1
    Providing IDs is e.g. a common technique to improve JPA performance. It also helps when you need unique IDs that do not follow the increment-pattern implemented for auto-generated keys - typical use-case is syncing independent data sources. – ChriWeis Aug 13 '12 at 09:00