gpt4 book ai didi

java - 如何将 Hibernate 验证注释与枚举一起使用?

转载 作者:搜寻专家 更新时间:2023-10-30 20:55:05 26 4
gpt4 key购买 nike

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

enum UserRole {
USER, ADMIN;
}

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

最佳答案

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

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


编辑

对于那些想要非 Guava 版本的人来说,它应该与类似的东西一起工作:

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 - 如何将 Hibernate 验证注释与枚举一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18205787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com