Generating unique keys using RandomStringUtils of apache commons
Solution 1
A random sequence of strings will always have a possibility of repeating, otherwise it's not really random. RandomStringUtils
is not really random, but it's trying to be as close to random as it can be, which seems contrary to your goal. If you must use randomly generated keys, then you should at least use java.util.UUID.randomUUID because that is made to be used that way.
You may find this link interesting: Generating unique IDs
Solution 2
No, random doesn't mean unique. You can try using UUIDs to generate unique keys.
Solution 3
You can do it with RandomStringUtils, but you also have to test the id before trying to insert it.
- Generate
- Does it already exist?
if yes goto 1 if no insert id
An UUID is very long and might not be what you want.
нαƒєєz
Updated on July 09, 2022Comments
-
нαƒєєz almost 2 years
Please find the below code which I've used to generate random strings using RandomStringUtils of apache commons.
String key = RandomStringUtils.random(5, String.valueOf(System.currentTimeMillis()));
I am limiting the key to 5 characters. My purpose is generating unique keys for each records when I'm inserting a new record to DB. Will the above code be suitable for corresponding task and could I be assured that I will get a unique key from the above code each time inserting a new record.