A Java application with PostgreSQL as RDBMS (used through plain JDBC) uses composite, consecutive numbers like
[CustomerNumber]-[Year]-[ConsecutiveNumber] in which
[ConsecutiveNumber] starts again with 1 for each new customer and each new year. Formatted as a String the numbers look like
There is a UNIQUE constraint in a DB table to make sure that each combination of customer number, year and consecutive number can only exist once.
The next free number to assign is determined as (
Select Max(ConsecutiveNumber) From XYZ Where CustomerNumber=? And Year=?)+
1. This only works due to locking / synchronization and the fact, that there is only one server software instance at a time (no horizontal scalability, i.e. chance to run the application on multiple servers with a load balancer in front).
Of course one could just leave out synchronization but then a lot of transactions / commits would fail due to unique constraint violations.
What approach do you suggest for the generation of such composite unique numbers?
As there can be unlimited customer numbers and years, it seems to be not feasible to create a dedicated DB SEQUENCE for each customer number / year combination.
I thought of using a dedicated
Connection / transaction just for the INSERT of a newly generated number to reduce the probability that it has already been taken by a different thread / in a concurrent transaction. But this would lead to inconsistent data (“ghost numbers”) if the actual business transaction does not commit for any reason.