继承类的不同验证策略

时间:2013-09-19 13:03:15

标签: java spring hibernate validation

如何为这样的类配置不同的验证政治:

   @MappedSuperClass
    public class Base{
       @Size(min=4)
       String name;
   }

所以:

public class Child extends Base{
   @NotBlank
   String surname;
}

如果我创建Base类,我想关闭验证。 但是如果我创建Child类,我想要启用验证。

我怎么能这样?

更新

我使用spring class BindingResult

进行验证

1 个答案:

答案 0 :(得分:1)

您可以定义两个validation groups,例如BaseGroup和ChildGroup。然后,您始终可以仅使用ChildGroup验证对象,因此在基类的情况下,将省略所有检查。

更新。示例:

 @MappedSuperClass
 public class Base{
    @Size(min=4, groups = BaseGroup.class)
    String name;
}

public class Child extends Base{
    @NotBlank(groups = ChildChecks.class)
    String surname;
} 

Base base = new Base();
Set<ConstraintViolation<Base>> baseViolations = validator.validate( base , ChildChecks.class);
// I suppose that this list will always be empty, because no constraints are defined for ChildChecks group in Base class

Child child = new Child();
Set<ConstraintViolation<Child>> childViolations = validator.validate( child,  BaseGroup.class, ChildChecks.class );
// All checks wil be verified here, because we use two groups