如何使用Hibernate验证注释与枚举? [英] How to use Hibernate validation annotations with enums?
问题描述
我如何使用Hibernate注解来验证枚举成员场?
以下不工作:
枚举的UserRole {
USER,ADMIN;
}类User {
@NotBlank // HV000030:没有验证可以为类型中找到:UserRole的。
UserRole的UserRole的;
}
请注意,你也可以创建一个验证器来检查字符串是枚举的一部分。
公共枚举用户类型{人员,公司}@NotNull
@StringEnumeration(enumClass = UserCivility.class)
私人字符串称号;
@Documented
@Constraint(validatedBy = StringEnumerationValidator.class)
@Target({METHOD,FIELD,ANNOTATION_TYPE,参数,CONSTRUCTOR})
@Retention(运行时)
公共@interface StringEnumeration { 字符串消息()默认的{} com.xxx.bean.validation.constraints.StringEnumeration.message;
类<> []群()默认{};
类&LT ;?扩展有效载荷GT; []的有效载荷()默认{}; 类&LT ;?扩展Enum<>> enumClass();}
公共类StringEnumerationValidator实现ConstraintValidator< StringEnumeration,字符串> { 私人设置<串GT; AVAILABLE_ENUM_NAMES; @覆盖
公共无效初始化(StringEnumeration stringEnumeration){
类&LT ;?扩展Enum<>> enumSelected = stringEnumeration.enumClass();
//设置&LT ;?扩展Enum<>> enumInstances = EnumSet.allOf(enumSelected);
SET&LT ;?扩展Enum<>> enumInstances = Sets.newHashSet(enumSelected.getEnumConstants());
AVAILABLE_ENUM_NAMES = FluentIterable
。从(enumInstances)
.transform(PrimitiveGuavaFunctions.ENUM_TO_NAME)
。设置();
} @覆盖
公共布尔的isValid(字符串值,ConstraintValidatorContext上下文){
如果(价值== NULL){
返回true;
}其他{
返回AVAILABLE_ENUM_NAMES.contains(值);
}
}}
这是很好的,因为你不松错误值的信息。你可以像
消息
值someBadUserType不是一个有效的用户类型。有效用户等级和积分
值是:人员,公司
块引用>修改
对于那些谁想要一个非番石榴版本它应该是这样工作的:
公共类StringEnumerationValidator实现ConstraintValidator< StringEnumeration,字符串> { 私人设置<串GT; AVAILABLE_ENUM_NAMES; 公共静态设置<串GT; getNamesSet(类&LT ;?扩展Enum<>> e){
枚举<> [] =枚举e.getEnumConstants();
的String [] =名新的String [enums.length]
的for(int i = 0; I< enums.length;我++){
名称由[i] =枚举[I]。名称();
}
SET<串GT; MYSET =新的HashSet<串GT;(Arrays.asList(地名));
返回MYSET;
} @覆盖
公共无效初始化(StringEnumeration stringEnumeration){
类&LT ;?扩展Enum<>> enumSelected = stringEnumeration.enumClass();
AVAILABLE_ENUM_NAMES = getNamesSet(enumSelected);
} @覆盖
公共布尔的isValid(字符串值,ConstraintValidatorContext上下文){
如果(价值== NULL){
返回true;
}其他{
返回AVAILABLE_ENUM_NAMES.contains(值);
}
}}和自定义错误消息,并显示相应的值,看看这个: http://stackoverflow.com/a/19833921/ 82609
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
The value "someBadUserType" is not a valid UserType. Valid UserType values are: PERSON, COMPANY
Edit
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); } } }
And to customize the error message and display the appropriate values, check this: http://stackoverflow.com/a/19833921/82609
这篇关于如何使用Hibernate验证注释与枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!