javax.validation:接收一个错误'无法找到类型的验证器:'
-
23-10-2019 - |
题
框架:jQuery,Spring,Hibernate,Hibernate验证器(JSR-303 BEAN验证)
平台:Windows
我正在尝试使用JSR 303-BEAN验证来定义自定义约束@idmustexist。约束的目的是检查关联表中是否存在输入的ID值。我正在收到一个错误'javax.validation.neppedtypeexception:对于类型:com.mycompany.myapp.domain.package.package1.class1'都找不到验证器。
如果我将@idmustexist放在class1的字段定义上(如下示例代码中所述),则会收到上述错误。但是,如果我将@idmustexist约束放在字符串字段上,则不会收到上述错误。我的代码在idmustexistValidator.java中崩溃。我不明白为什么Hibernate可以找到“字符串”类的验证器,而不能找到域类“ Class1”。
我的班级定义如下。
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(请注意,此类设计具有错误)
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);
}
解决方案
您的约束验证器被声明以验证 Serializable
值。也许 Class2
不是 Serializable
?
不隶属于 StackOverflow