使用集时违反约束 属性 路径

Constraint Violation Property Path when using Sets

我无法解决我遇到的关于 JSR303 bean 验证要求的问题(我目前正在使用 Hibernate Validator)。

假设我有以下领域模型

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

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

class Bar {
   private String name;

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

假设我有一个 foo 实例,其中有两个 bar,其中两个名称之一为空。验证 foo 后,我手上拿着 @NotBlank 约束违规,其中 属性 路径 bars[].name。一切都很好,但是...

有什么方法可以找出两个栏中的哪一个名称为空?或者我是否被迫在这里使用 List 并使用反射反省 - 然后是唯一 - 属性 路径?

Hibernate Validator 的最新版本,5.2.0.CR1, provides a solution。您可以展开 属性 路径节点并获取 属性 值。这样你就知道哪个 Bar 实例受到影响:

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();