【问题标题】:Hibernate Validation - how to get annotation type?Hibernate Validation - 如何获取注释类型?
【发布时间】:2019-02-12 12:23:34
【问题描述】:

这是我要验证的 TO 类:

public class Person {

    @NotNull
    private String name;

    @NotNull
    @Pattern(regexp = ID.REGEX)
    private String id;

    public Person(String name, String id) {
        this.name = name;
        this.id = id;
    }
}

及验证方法:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Person person = new Person(null, "notCorrextIdRegex");
validator.validate(person).stream().forEach(constraintViolation -> {
    ...
}

是否可以轻松获取验证失败的注解类型?我需要这个来创建具有各种错误代码的异常,具体取决于constraintViolation,例如:

@NotNull -> new Exception("Object is null or empty.")

这是实现它的好方法吗?

【问题讨论】:

    标签: hibernate validation


    【解决方案1】:

    您可以使用分组序列(有关信息和示例,请参阅the docs on chapter 2.3.1)将您的约束(使用groups 属性)按您的喜好分组。

    【讨论】:

    • 将您的评论作为答案并接受它,这样如果没有用,我可以删除我的。
    猜你喜欢
    • 1970-01-01
    • 2011-10-28
    • 2016-02-03
    • 1970-01-01
    • 2011-01-12
    • 2013-09-13
    • 1970-01-01
    • 2021-05-13
    • 2011-06-03
    相关资源
    最近更新 更多