For simple custom constraints (which do not make a DB call or need autowiring inside the validation class), please refer to here. This Gist is about how to make Database calls through autowired Spring JPA Repositories as part of the constraint validation.
Use Case:
- My Table has 3 columns - id, role and user_id. Now there can be only 1 row for which role can take the value ROLE_ROOT. And once that record is inserted, it can't be updated.
How I am implementing:
- Using custom javax.validation.ConstraintValidator and checking if record is present for role=ROLE_ROOT inside isValid
(There are alternatives to do this, like, before calling repository.save(..)
, call repository.findByRole(..)
, check and restrict.)