ramowa: JQuery, Spring, Hibernate, Hibernate Validator (JSR-303 Bean Validation)
Platforma: Windowsjavax.validation: komunikat o błędzie 'Nie można odnaleźć walidator dla typu:'
Próbuję zdefiniuj niestandardowe ograniczenie @IdMustExist za pomocą JSR 303-Bean Validation. Celem ograniczenia jest sprawdzenie, czy wprowadzona wartość id istnieje w powiązanej tabeli. Pojawia się błąd "javax.validation.UnexpectedTypeException: Nie znaleziono walidatora dla typu: com.mycompany.myapp.domain.package1.class1".
Jeśli umieść @IdMustExist na definicji pola klasy 1 (jak podano w poniższym przykładzie kodu), otrzymuję powyższy błąd. Ale jeśli umieszczę ograniczenie @IdMustExist w polu String, nie otrzymam powyższego błędu. Mój kod ulega awarii w IdMustExistValidator.java. Nie rozumiem, dlaczego Hibernate może znaleźć Validator dla klasy "String", ale nie dla klasy domeny "Class1".
Moje definicje klas są następujące.
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 (Należy pamiętać, że klasa ta konstrukcja ma błędów)
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);
}
Masz rację. Moja Class2 nie implementowała Serializable. Dzięki! dużo. – Jayaprakash
Czy to nie Class1 powinien implementować interfejs Serializable? Lub obie klasy? – Stephane