【问题标题】:Annotation for a class inside another class while using Hibernate Validator使用 Hibernate Validator 时对另一个类中的类进行注释
【发布时间】:2018-01-20 03:40:00
【问题描述】:

我正在使用 Hibernate Validator API 对一个名为 Supplier_Registration 的表进行服务器端验证。对应的 Java 类如下所示。它的成员之一是另一个名为 Address 的类。我需要为Address 使用什么注释,以便Address 类的成员也得到验证?非常感谢。

public class Registration implements Serializable {
    private static final long serialVersionUID = 3380401999460628270L;
    private static final String EMAIL_PATTERN =
            "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    @NotNull(message="{legalName_notnull}")
    @Size(min=1, max=255, message="{legalName_not_to_exceed}")

    private String legalName;

    @NotNull(message="{adminFirstName_notnull}")
    @Size(min=1, max=40, message="{adminFirstName_not_to_exceed}")
    private String adminFirstName;


    @NotNull(message="{adminLastName_notnull}")
    @Size(min=1, max=40, message="{adminLastName_not_to_exceed}")
    private String adminLastName;

    @NotNull(message="{adminEmail_notnull}")
    @Size(min=1, max=255, message="{adminEmail_not_to_exceed}")
    @Pattern(regexp=EMAIL_PATTERN, message="{adminEmail_not_valid}")
    private String adminEmail;

    @NotNull(message="{reEnterEmail_notnull}")
    @Size(min=1, max=255, message="{reEnterEmail_not_to_exceed}")
    @Pattern(regexp=EMAIL_PATTERN, message="{reEnterEmail_not_valid}")

    private String reEnterEmail;

    @NotNull(message="{phoneCountryNumber_notnull}")
    @Size(min=1, max=5, message="{phoneCountryNumber_not_to_exceed}")
    private String phoneCountryNbr;

    @NotNull(message="{phoneNumber_notnull}")
    @Size(min=1, max=18, message="{phoneNumber_not_to_exceed}")
    private String phoneNumber;

    @NotNull(message="{dunsNumber_notnull}")
    @Size(min=1, max=9, message="{dunsNumber_not_to_exceed}")
    private String dunsNumber;

    private Address address;

【问题讨论】:

    标签: hibernate class validation annotations


    【解决方案1】:

    您要执行的这种验证称为级联验证。要验证address,您需要在address 属性上使用@Valid 注释。此外,如果address 是强制性的(意味着如果该字段不能为空),您也可以使用@NotNull。所以你会有这样的东西:

    public class Registration implements Serializable {
        // all other properties ...
    
        @Valid // this one is requred if you want address constraints to be validated
        @NotNull // this one is optional - use it in case if address is a mandatory field
        private Address address;
    }
    

    您可以在此处的文档中找到有关级联验证的所有信息 - Object graphs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多