gpt4 book ai didi

hibernate - javax.validation : Receive an error 'No validator could be found for type:'

转载 作者:行者123 更新时间:2023-12-04 20:22:32 26 4
gpt4 key购买 nike

框架:JQuery、Spring、Hibernate、Hibernate Validator(JSR-303 Bean Validation)
平台:Windows

我正在尝试使用 JSR 303-Bean 验证定义自定义约束 @IdMustExist。约束的目的是检查输入的 id 值是否存在于关联表中。我收到错误“javax.validation.UnexpectedTypeException:找不到类型 validator :com.mycompany.myapp.domain.package1.class1”。

如果我将 @IdMustExist 放在 Class1 的字段定义上(如下面的示例代码所示),我会收到上述错误。但是,如果我在 String 字段上放置 @IdMustExist 约束,则不会收到上述错误。我的代码在 IdMustExistValidator.java 中崩溃。我不明白为什么 Hibernate 可以为“String”类找到 validator ,但不能为域类“Class1”找到 validator 。

我的类定义如下。

Class2.java

@Entity
@Table
public class Class2 extends BaseEntity {
/**
* Validation: Class1 Id must exist.
*/
@ManyToOne
@JoinColumn(name="Class1Id")
@IdMustExist(entity=Class1.class)
private Class1 class1;

..

IdMustExist.java
@Required
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = IdMustExistValidator.class)
@Documented
@ReportAsSingleViolation
public @interface IdMustExist {
String message() default "{com.mycompany.myapp.domain.validation.constraints.idmustexist}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};

/**
* The entity class that contains the id property.
*/
Class<?> entity();

/**
* The property of the entity we want to validate for existence. Default value is "id"
*/
String idProperty() default "id";
}

IdMustExistValidator.java(请注意这个类设计有bug)
public class IdMustExistValidator implements ConstraintValidator<IdMustExist, Serializable> {

/**
* Retrieve the entity class name and id property name
*/
public void initialize(IdMustExist idMustExist) {
if (idMustExist.entity() != null)
entity = idMustExist.entity();
idProperty = idMustExist.idProperty();
}

/**
* Retrieve the entity for the given entity class and id property.
* If the entity is available return true else false
*/
public boolean isValid(Serializable property, ConstraintValidatorContext cvContext) {
logger.debug("Property Class = {}", property.getClass().getName());
logger.debug("Property = {}", property);
List resultList = commonDao.getEntityById(entity.getName(), idProperty);
return resultList != null && resultList.size() > 0;
}

private Class<?> entity;
private String idProperty;

@Autowired
private CommonDao commonDao;
private final Logger logger = LoggerFactory.getLogger(IdMustExistValidator.class);

}

最佳答案

您的约束 validator 被声明为验证 Serializable值。
也许 Class2不是 Serializable ?

关于hibernate - javax.validation : Receive an error 'No validator could be found for type:' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4774954/

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