Java 不同的固有类验证策略

Java 不同的固有类验证策略,java,spring,hibernate,validation,Java,Spring,Hibernate,Validation,如何为so类配置不同的验证策略: @MappedSuperClass public class Base{ @Size(min=4) String name; } 因此: public class Child extends Base{ @NotBlank String surname; } 如果我创建基类,我希望关闭验证。 但如果我创建子类,我希望打开验证 我怎么能这样呢 更新 我使用spring类的BindingResult进行

如何为so类配置不同的验证策略:

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

public class Child extends Base{
   @NotBlank
   String surname;
}
如果我创建基类,我希望关闭验证。 但如果我创建子类,我希望打开验证

我怎么能这样呢

更新

我使用spring类的BindingResult进行验证,您可以定义两个,例如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
@MappedSuperClass
公共阶级基础{
@大小(最小值=4,组数=BaseGroup.class)
字符串名;
}
公共类子扩展基{
@NotBlank(组=ChildChecks.class)
串姓;
} 
基础=新基础();
Set baseViolations=validator.validate(base,ChildChecks.class);
//我假设这个列表总是空的,因为基类中没有为ChildChecks组定义任何约束
子项=新子项();
Set childinvalitions=validator.validate(child、BaseGroup.class、ChildChecks.class);
//所有检查都将在此处验证,因为我们使用两个组
您可以定义两个,例如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
@MappedSuperClass
公共阶级基础{
@大小(最小值=4,组数=BaseGroup.class)
字符串名;
}
公共类子扩展基{
@NotBlank(组=ChildChecks.class)
串姓;
} 
基础=新基础();
Set baseViolations=validator.validate(base,ChildChecks.class);
//我假设这个列表总是空的,因为基类中没有为ChildChecks组定义任何约束
子项=新子项();
Set childinvalitions=validator.validate(child、BaseGroup.class、ChildChecks.class);
//所有检查都将在此处验证,因为我们使用两个组

@user2674303我的response@user2674303我在回复中固定了列表行