Constraint Violation Property Path when using Sets

3.2k views Asked by At

I can't get my mind to wrap around a problem I have with a requirement concerning JSR303 bean validation (I'm currently using Hibernate Validator).

Assuming I have the following domain model

class Foo {
   private Set<Bar> bars = new HashSet<>();

   @Valid
   public Set<Bar> getBars() { ... }
}

class Bar {
   private String name;

   @NotBlank
   public String getName() { ... }
}

Say I have a foo instance with two bars with one of the two names being empty. After validating foo I'm holding a @NotBlank constraint violation with a property path bars[].name in my hand. Which is all well, but...

is there any way I can find out which of the two bars had its name empty? Or am I forced to use a List here and introspect the - then unique - property path using reflection?

1

There are 1 answers

1
Gunnar On BEST ANSWER

The latest release of Hibernate Validator, 5.2.0.CR1, provides a solution for this. You can unwrap property path nodes and get the property value. That way you know which Bar instance is affected:

Set<ConstraintViolation<Foo>> constraintViolations = ...;

Path path = constraintViolations.iterator().next().getPropertyPath();
Iterator<Path.Node> nodeIterator = path.iterator();

Path.Node node = nodeIterator.next();
Bar bar = (Bar) node.as( PropertyNode.class ).getValue();