116

我正在使用 JPA 2.0/Hibernate 验证来验证我的模型。我现在有一种情况,必须验证两个字段的组合:

public class MyModel {
    public Integer getValue1() {
        //...
    }
    public String getValue2() {
        //...
    }
}

如果两者和都有效,则模型无效getValue1()getValue2()null

如何使用 JPA 2.0/Hibernate 执行这种验证?使用简单的@NotNull注释,两个 getter 都必须为非 null 才能通过验证。

4

5 回答 5

121

对于多个属性验证,您应该使用类级别的约束。来自 Bean Validation Sneak Peek 第二部分:自定义约束

类级约束

你们中的一些人对应用跨越多个属性的约束或表达依赖于多个属性的约束的能力表示担忧。经典的例子是地址验证。地址有复杂的规则:

  • 街道名称有点标准,当然必须有长度限制
  • 邮政编码结构完全取决于国家
  • 城市通常可以与邮政编码相关联,并且可以进行一些错误检查(前提是可以访问验证服务)
  • 由于这些相互依赖关系,一个简单的属性级别约束确实可以满足要求

Bean Validation 规范提供的解决方案有两个方面:

  • 它提供了通过使用组和组序列来强制在另一组约束之前应用一组约束的能力。这个主题将在下一篇博客文章中介绍
  • 它允许定义类级别的约束

类级别约束是适用于类而不是属性的常规约束(注释/实现二重奏)。换句话说,类级约束接收对象实例(而不是属性值)isValid

@AddressAnnotation 
public class Address {
    @NotNull @Max(50) private String street1;
    @Max(50) private String street2;
    @Max(10) @NotNull private String zipCode;
    @Max(20) @NotNull String city;
    @NotNull private Country country;
    
    ...
}

@Constraint(validatedBy = MultiCountryAddressValidator.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface AddressAnnotation {
    String message() default "{error.address}";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };
}

public class MultiCountryAddressValidator implements ConstraintValidator<AddressAnnotation, Address> {
    public void initialize(AddressAnnotation constraintAnnotation) {
    // initialize the zipcode/city/country correlation service
    }

    /**
     * Validate zipcode and city depending on the country
     */
    public boolean isValid(Address object, ConstraintValidatorContext context) {
        if (!(object instanceof Address)) {
            throw new IllegalArgumentException("@AddressAnnotation only applies to Address objects");
        }
        Address address = (Address) object;
        Country country = address.getCountry();
        if (country.getISO2() == "FR") {
            // check address.getZipCode() structure for France (5 numbers)
            // check zipcode and city correlation (calling an external service?)
            return isValid;
        } else if (country.getISO2() == "GR") {
            // check address.getZipCode() structure for Greece
            // no zipcode / city correlation available at the moment
            return isValid;
        }
        // ...
    }
}

高级地址验证规则已被排除在地址对象之外并由 MultiCountryAddressValidator. 通过访问对象实例,类级约束具有很大的灵活性,并且可以验证多个相关属性。请注意,这里的等式忽略了排序,我们将在下一篇文章中回到它。

专家组讨论了各种多属性支持方法:我们认为类级别约束方法与其他涉及依赖关系的属性级别方法相比提供了足够的简单性和灵活性。欢迎您的反馈。

于 2010-05-06T19:30:54.913 回答
46

为了与Bean Validation正常工作,Pascal Thivent 的答案中提供的示例可以重写如下:

@ValidAddress
public class Address {

    @NotNull
    @Size(max = 50)
    private String street1;

    @Size(max = 50)
    private String street2;

    @NotNull
    @Size(max = 10)
    private String zipCode;

    @NotNull
    @Size(max = 20)
    private String city;

    @Valid
    @NotNull
    private Country country;

    // Getters and setters
}
public class Country {

    @NotNull
    @Size(min = 2, max = 2)
    private String iso2;

    // Getters and setters
}
@Documented
@Target(TYPE)
@Retention(RUNTIME)
@Constraint(validatedBy = { MultiCountryAddressValidator.class })
public @interface ValidAddress {

    String message() default "{com.example.validation.ValidAddress.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
public class MultiCountryAddressValidator 
       implements ConstraintValidator<ValidAddress, Address> {

    public void initialize(ValidAddress constraintAnnotation) {

    }

    @Override
    public boolean isValid(Address address, 
                           ConstraintValidatorContext constraintValidatorContext) {

        Country country = address.getCountry();
        if (country == null || country.getIso2() == null || address.getZipCode() == null) {
            return true;
        }

        switch (country.getIso2()) {
            case "FR":
                return // Check if address.getZipCode() is valid for France
            case "GR":
                return // Check if address.getZipCode() is valid for Greece
            default:
                return true;
        }
    }
}
于 2017-06-02T10:21:24.080 回答
13

当您想保持 Bean Validation 规范时,可以使用自定义类级别验证器,例如此处

如果您乐于使用 Hibernate Validator 功能,您可以使用自 Validator-4.1.0.Final 起提供的@ScriptAssert。其 JavaDoc 除外:

脚本表达式可以用任何脚本或表达式语言编写,在类路径中可以找到与JSR 223 (“JavaTM 平台脚本”)兼容的引擎。

例子:

@ScriptAssert(lang = "javascript", script = "_this.value1 != null || _this != value2)")
public class MyBean {
  private String value1;
  private String value2;
}
于 2010-12-06T14:43:27.933 回答
4

您可以使用@AssertTrue这样的验证:

public class MyModel {
    
    // values

    @AssertTrue(message = "Values are invalid")
    private String isValid() {
      return value1 != null || value2 != null;
    }
}
于 2021-11-11T15:35:55.670 回答
0

编程语言:Java

这是一个帮助我的解决方案。

要求 :

  1. 在 UI 上有一个包含对象列表的表,该表映射到具有 fk 关系的多个表/对象。

  2. 现在验证不在多个 fks 中,只有 3 列不能重复。我的意思是3的组合不能重复。

注意:当我在 Java 上开发自定义框架时,没有使用 HashCode 或 equals 的选项。如果我将使用数组索引迭代会增加我不想要的时间复杂度。

解决方案:

我准备了一个字符串,它是一个自定义字符串,其中包含 FK1 的 ID#ID 的 FK2#ID 的 FK3 例如:字符串将形成 -> 1000L#3000L#1300L#

这个字符串,我们将使用 set 的 add() 添加到一个集合中,如果出现重复,它将返回 false。

基于这个标志,我们可以抛出验证消息。

这对我有帮助。某些情况和限制出现在 DS 可能无济于事的地方。

于 2021-06-02T14:39:58.153 回答