What I have done in a similar situation with Hibernate (don't know if it is the best way) is something like the following:
In your custom annotation add a constraint annotation with a validating class:
@Constraint (validatedBy = UniqueIdValidator.class)
public @interface CustomAnnotation
Then I have created the UniqueIdValidator class (I used array
as field instead of List
like you do, but I hope it works)
public class UniqueIdValidator implements ConstraintValidator<CustomAnnotation, List<String>>
with the method:
@Override
public boolean isValid(List<String> values, ConstraintValidatorContext constraintContext)
in this method you can check if your List
contains duplicates and throw an exception or use the error handling features, like adding a message to the constraintContext
like they do in the link I added above.
To find the duplicates you can do it like this i.e.