javax.validation: получить ошибку «Валидатор не может быть найден для типа: '

StackOverflow https://stackoverflow.com/questions/4774954

Вопрос

Кампуль: jQuery, Spring, Hibernate, Hibernate Validator (JSR-303 Validation)
Платформа: Windows

Я пытаюсь определить пользовательское ограничение @idmustexist, используя проверку JSR 303-Bean. Цель ограничения состоит в том, чтобы проверить, существует ли введенное значение идентификатора в связанной таблице. Я получаю ошибку 'javax.validation.unexpectedtypeexception: не может быть найдено валидатора для типа: com.mycompany.myapp.domain.package1.class1'.

Если я размещаю @idmustexist в определение поля класса1 (как приведено в примере кода ниже), я получаю вышеуказанную ошибку. Но если я помесчу ограничения @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?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top