使用集时的约束违例属性路径

时间:2015-06-10 12:16:31

标签: java hibernate-validator

我无法理解我遇到的有关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的{​​{1}}约束违规。这一切都很好,但是......

有什么方法可以找出这两个酒吧中哪一个名字为空?或者我被迫在这里使用bars[].name并使用反射内省 - 然后是唯一的 - 属性路径?

1 个答案:

答案 0 :(得分:2)

最新版本的Hibernate Validator 5.2.0.CR1为此提供了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();