0

I need to write custom annotation for UniqueElements. I know Hibernate provides one of these, but I need to validate by just one parameter (so can not use hashCode).

I have something like this:

@CustomAnnotatinon
List<MyParameter> parameters;

Lets say MyParameter have id, value and type, but I have to validate unique elements only by id. Can somebody please help me?

Noskol
  • 315
  • 4
  • 17

1 Answers1

2

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.

Jack Flamp
  • 1,223
  • 1
  • 16
  • 32
  • Thanks :) To be hones I got something very similar but was not sure if should I take List as argument or try to get List + last added value to that list. – Noskol Sep 20 '18 at 08:53