gpt4 book ai didi

hibernate - 电子邮件字符串集合的 JPA 验证

转载 作者:行者123 更新时间:2023-12-04 22:19:43 24 4
gpt4 key购买 nike

我的 bean 中有一个 String 列表。这些字符串是电子邮件,我想验证它们。

@Email
@ElementCollection(fetch = FetchType.LAZY)
@OrderColumn
private List<String> emails = new ArrayList<String>();

在执行时,我收到此错误:
Caused by: javax.validation.UnexpectedTypeException: HV000030: No validator could be found for type: java.util.List<java.lang.String>.
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.verifyResolveWasUnique(ConstraintValidatorManager.java:218)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.findMatchingValidatorClass(ConstraintValidatorManager.java:193)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.getInitializedValidator(ConstraintValidatorManager.java:97)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:125)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateComposingConstraints(ConstraintTree.java:233)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:102)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:91)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:83)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:547)
...

这样做的正确方法是什么?或者有没有其他方法可以做到这一点?

最佳答案

@Email仅适用于String而不适用于List,但您可以创建自己的 validator :

@Target({ ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EmailCollectionValidator.class)
@Documented
public @interface EmailCollection {
String message() default "Invalid Email";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}

validator :
public class EmailCollectionValidator implements ConstraintValidator<EmailCollection, Collection<String>> {

@Override
public void initialize(EmailCollection constraintAnnotation) {

}

@Override
public boolean isValid(Collection<String> value, ConstraintValidatorContext context) {
if (value == null) {
return false;
}
EmailValidator validator = new EmailValidator();
for (String s : value) {
if (!validator.isValid(s, context)) {
return false;
}
}
return true;
}
}

执行:
@EmailCollection
@ElementCollection(fetch = FetchType.LAZY)
@OrderColumn
private List<String> emails = new ArrayList<String>();

关于hibernate - 电子邮件字符串集合的 JPA 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35050936/

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