I want to issue unique numbers to customers that are non sequential. These numbers will be used as an id to log into my web application.
...
For security reasons, the numbers can't be sequential, nor can I use an email address. I've done something similar once (not in
Java).
1. Generate a random number.
2. Select against the table to make sure that the random number doesn't already exist on the table. If it does, generate a new random number (go back to step 1).
3. Insert row with the random number.
4. Commit
In my case, I was working in a nonmultithreading, nonmultitasking environment, so I was confident that between steps 2 and 3, nothing else could have inserted that same number into the table.
Also, you probably want to have an index on the random number column for performance reasons. As the table gets larger, step 2 can get costlier.
Also, don't forget step 4 -- committing after each insert. Otherwise, you could have a potentially matching random number in the insert/commit buffer that would not be detected by the select in step 2.
Also, instead of the select
test in step 2 you could just insert without the check if you have a unique constraint set up on the random-number column and catch the unique constraint error. (This was not an option for me in the stuff I was working on.)