JSR-303不支持这种情况吗?

问题描述 投票:0回答:2

我尝试通过Hibernate Validator验证bean。它应该是可编程的并且基于JSON配置文件。数据模型:

class A {
    field,
    other fields
}
class B {
    class A a,
    other fields
}
class C {
    class A a,
    other fields
}
class D {
    class B b,
    class C c,
    other fields
}

根据JSON配置文件验证D.配置文件要验证以下内容:D.b.a.field不应为null。 D.c.a.field可以为空。

使用程序方式,我设置验证如下:

constraintMapping
    .type( D.class )
        .property( "b", FIELD )
            .constraint( new NotNullDef() )
            .valid()
.type( B.class )
    .property( "a", FIELD )
        .constraint( new NotNullDef() )
        .valid()
.type ( A.class )
    .property( "field", FIELD )
        .constraint( new NotNullDef() );

现在,A.field已被设置为不为null验证器,但问题是,现在D.c.a.filed也不能为null。

这只是一个例子,我绝对不想改变数据模型。

bean-validation
2个回答
0
投票

在约束级别使用组可以帮助您解决问题。要将组添加到约束,您只需调用group方法并传递应包含约束的组列表:

constraintMapping
    .type( D.class )
        .property( "b", FIELD )
            .constraint( new NotNullDef().groups( SomeGroup.class )
            .valid()

然后,您可以为不同的“验证路径”创建不同的组,并在验证对象时使用它们。如果您的验证配置完全是动态的,那么Thant可能效果不佳。另外请参阅doc以获取有关组的更多信息。


0
投票

@ mark-o,我测试了以下解决方案,但我失败了。它验证了GroupB和GroupC的field1和field2,但我的期望是仅对GroupB验证field1而对GroupC不验证,并且仅对GroupC验证field2,而对GroupB验证field2。

对A类(具有field1和field2)稍作改动,并为A类添加一个包装,由B类和C类使用. constraintMapping .type( D.class ) .property( "b", FIELD ) .constraint( new NotNullDef().groups(GroupB.class) ) .valid() .property( "c", FIELD ) .constraint( new NotNullDef().groups(GroupC.class) ) .valid() .type( B.class ) .property( "aWrapper", FIELD ) .constraint( new NotNullDef().groups(GroupB.class) ) .valid() .type( C.class ) .property( "aWrapper", FIELD ) .constraint( new NotNullDef().groups(GroupC.class) ) .valid() .type ( AWrapper.class ) .property( "a", FIELD ) .constraint( new NotNullDef().groups(GroupB.class, GroupC.class) ) .valid() .type ( A.class ) .property( "field1", FIELD ) .constraint( new NotNullDef().groups(GroupB.class) ) .property( "field2", FIELD ) .constraint( new NotNullDef().groups(GroupC.class) );

© www.soinside.com 2019 - 2024. All rights reserved.