Have table for storing some unique identifiers. My first idea was to have incremental counter column for every single identifier prefix like this:
ID IDENTIFIER COUNTER
1 B-1 1
2 A-1 1
3 A-2 2
4 A-3 3
5 B-2 2
6 BBA-1 1
7 BBA-2 2
Every identifier is prefixed by letter or combination of letters and extended by some incremental number. For example, if I want to add a new identifier with A- prefix, have to select max value of counter where IDENTIFIER
starts with 'A-', returned value increment by one, concatenate it with searched prefix and persist to database.
With this approach I'm afraid of concurrency issues when two parallel threads grab the same value of counter, uniqueness rule would be violated.
How can I prevent this? Is it better approach to have two tables where one would only take care of individual counter for every identifier base, like this:
BASE COUNTER
A 3
B 2
BBA 2
Does Spring or JPA have some mechanism for dealing with this? First idea I have at the moment is optimistic locking and @Version
annotation. Would it be useful because I already have JPA mappings in my project?