I did some performance tests and from what I tested it is faster to try to insert something that is supposed to contain a unique ID (that a customer may provide) and let it fail compared to checking if the value the customer did provide is really not used, yet and then inserting it.
The only thing I’m struggling with is that if I have a list of 10 IDs where the system is always taking the next ID and uses it the Insert will fail with a UniqueConstraintViolationException which I can catch. In this case I’d like to just retry it with the next number from that list. The issue I have is that the EntityManager gets closed when the exception is thrown which makes it impossible to simply get the next number from the database and retry it.
Is there any way to work around this (e.g. reopening the EntityManager) or should I try to find another way of handling it?