posted 7 months ago
I have a spring boot 3 project and have been looking into the various ways to deal with uniqueness checks before saving or updating a record. It looks like there is a few approaches, but broadly:
1. Run a pre-save/pre-update check for uniqueness and return a boolean
Cons here are : not atomic, not concurrent safe and extra db call
2. Let the db throw the exception and have it handled in Spring
I am mainly interested in the best way to implement #2. This is what I have so far
ENTITY
And the service - pretty standard update method - note I want the safety net of @Transactional.
And then on my controller
And finally the exception handler. This was the one that took the most experimenting. Note i had to use e.getCause().getCause() twice to drill down into the second level of the exception to confirm its a SQL Constraint Violation.
Gives a error like : `Duplicate entry 'Barry' for key 'car.uc_name'`
So questions:
1. Does this approach make sense and could it be improved - particularly the exception handling?
2. Are there other "common" SQL exceptions i should be checking for, i.e. instanceOf SQL.....
Thanks in advance.
Al