如何使用带有枚举的 Hibernate 验证注释?

How to use Hibernate validation annotations with enums?(如何使用带有枚举的 Hibernate 验证注释?)
本文介绍了如何使用带有枚举的 Hibernate 验证注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何使用休眠注释来验证枚举成员字段?以下方法不起作用:

How can I use hibernate annotations to validate an enum member field? The following does not work:

enum UserRole {
   USER, ADMIN;
}

class User {
   @NotBlank //HV000030: No validator could be found for type: UserRole.
   UserRole userRole;
}

推荐答案

请注意,您还可以创建一个验证器来检查字符串是否是枚举的一部分.

Note you can also create a validator to check a String is part of an enumeration.

public enum UserType { PERSON, COMPANY }

@NotNull
@StringEnumeration(enumClass = UserCivility.class)
private String title;

<小时>

@Documented
@Constraint(validatedBy = StringEnumerationValidator.class)
@Target({ METHOD, FIELD, ANNOTATION_TYPE, PARAMETER, CONSTRUCTOR })
@Retention(RUNTIME)
public @interface StringEnumeration {

  String message() default "{com.xxx.bean.validation.constraints.StringEnumeration.message}";
  Class<?>[] groups() default {};
  Class<? extends Payload>[] payload() default {};

  Class<? extends Enum<?>> enumClass();

}

<小时>

public class StringEnumerationValidator implements ConstraintValidator<StringEnumeration, String> {

  private Set<String> AVAILABLE_ENUM_NAMES;

  @Override
  public void initialize(StringEnumeration stringEnumeration) {
    Class<? extends Enum<?>> enumSelected = stringEnumeration.enumClass();
    //Set<? extends Enum<?>> enumInstances = EnumSet.allOf(enumSelected);
    Set<? extends Enum<?>> enumInstances = Sets.newHashSet(enumSelected.getEnumConstants());
    AVAILABLE_ENUM_NAMES = FluentIterable
            .from(enumInstances)
            .transform(PrimitiveGuavaFunctions.ENUM_TO_NAME)
            .toSet();
  }

  @Override
  public boolean isValid(String value, ConstraintValidatorContext context) {
    if ( value == null ) {
      return true;
    } else {
      return AVAILABLE_ENUM_NAMES.contains(value);
    }
  }

}

<小时>

这很好,因为您不会丢失错误值"的信息.您可以收到类似


This is nice because you don't loose the information of the "wrong value". You can get a message like

值someBadUserType"不是有效的用户类型.有效的用户类型值是:人员、公司

The value "someBadUserType" is not a valid UserType. Valid UserType values are: PERSON, COMPANY

<小时>

编辑

对于那些想要非 Guava 版本的人来说,它应该与以下内容一起使用:

For those who want a non-Guava version it should work with something like:

public class StringEnumerationValidator implements ConstraintValidator<StringEnumeration, String> {

  private Set<String> AVAILABLE_ENUM_NAMES;

  public static Set<String> getNamesSet(Class<? extends Enum<?>> e) {
     Enum<?>[] enums = e.getEnumConstants();
     String[] names = new String[enums.length];
     for (int i = 0; i < enums.length; i++) {
         names[i] = enums[i].name();
     }
     Set<String> mySet = new HashSet<String>(Arrays.asList(names));
     return mySet;
  }

  @Override
  public void initialize(StringEnumeration stringEnumeration) {
    Class<? extends Enum<?>> enumSelected = stringEnumeration.enumClass();
    AVAILABLE_ENUM_NAMES = getNamesSet(enumSelected);
  }

  @Override
  public boolean isValid(String value, ConstraintValidatorContext context) {
    if ( value == null ) {
      return true;
    } else {
      return AVAILABLE_ENUM_NAMES.contains(value);
    }
  }

}

要自定义错误消息并显示适当的值,请检查以下内容:https://stackoverflow.com/a/19833921/82609

And to customize the error message and display the appropriate values, check this: https://stackoverflow.com/a/19833921/82609

这篇关于如何使用带有枚举的 Hibernate 验证注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)