栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在枚举中使用Hibernate验证批注?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在枚举中使用Hibernate验证批注?

请注意,您还可以创建一个验证器来检查String是否为枚举的一部分。

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);    }  }}

这很好,因为您不会丢失“错误值”的信息。您会收到类似的消息

值“ someBadUserType”不是有效的用户类型。有效的UserType值是: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);    }  }}

并要自定义错误消息并显示适当的值,请检查以下内容:http://codingdict.com/questions/122937



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/438176.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号