Domanda

I have a list of lets say Car objects. Each car has a miles member. I need to validate (using Hibernate Validator) that at least one car in my list has a not null miles member. The best solution would be an annotation that would apply to all the elements of a collection, but would validate in the context of the whole collection.

I have two questions:

  • Is there already an annotation for this (I do not know of any)?
  • If there is no annotation for this, is there a way to create an generic annotation? I thought of specifiyng the name of the field that has to be not null at least for one element in the list, then I can apply this not only for Car classes.

    public class VechicleTransport {
    
        @AtLeastOneNotNull( fieldName = "miles" )
        private List<Car> carList;
    }
    
    
    public class Car {
    
      private Double miles;
    
        ....
    }
    
È stato utile?

Soluzione

AFAIK there is no such annotation, You need to define custom constraint annotations and define your validation logic inside it.
Like
Defining custom constraint annotation AtLeastOneNotNull

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy=AtLeastOneNotNullValidator.class)

public @interface AtLeastOneNotNull{
 String message() default "Your error message";
 Class<!--?-->[] groups() default {};
 Class<!--? extends Payload-->[] payload() default {};
}   

Defining validator for custom annotation.

public class AtLeastOneNotNullValidator implements ConstraintValidator<AtLeastOneNotNull, object=""> {

 @Override
 public void initialize(AtLeastOneNotNull constraint) {

 }

 @Override
 public boolean isValid(Object target, ConstraintValidatorContext context) {
    // Add logic to check if atleast one element have one field
 }
}

Link for more details

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top