java – 如何用枚举使用Hibernate验证注释?

前端之家收集整理的这篇文章主要介绍了java – 如何用枚举使用Hibernate验证注释?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何使用hibernate注释来验证枚举成员字段?
以下不起作用:
enum UserRole {
   USER,ADMIN;
}

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

解决方法

注意,您还可以创建一个验证器来检查字符串是枚举的一部分.
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);
    }
  }

}

这是很好的,因为你不会松动“错误的价值”的信息.你可以得到一个消息

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

编辑

对于那些想要非番石榴版本的人来说,它应该像以下一样工作:

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

猜你在找的Java相关文章