I use Spring and Spring MVC 3.1, Hibernate 3, Hibernate Validator 4.3.
I want to add my custom constraint validator, but it seems that my validator not called and always got "No validator could be found for type" exception. Did I make any mistake? I got a big problem of getting this exception always
javax.validation.UnexpectedTypeException: HV000030: No validator could be found for type: java.lang.String.
at org.hibernate.validator.internal.engine.ConstraintTree.verifyResolveWasUnique(ConstraintTree.java:394)
at org.hibernate.validator.internal.engine.ConstraintTree.findMatchingValidatorClass(ConstraintTree.java:375)
But if I remove my custom constraint validator, everything works fine. Here is my code, could you help find the source to cause this exception?
test.constraint.ActorConstraint
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy=ActorConstraintValidator.class)
public @interface ActorConstraint {
String message() default "Actor already exists in database";
public abstract Class<?>[] groups() default {};
public abstract Class<? extends Payload>[] payload() default {};
}
test.constraint.ActorConstraintValidator
@Component
public class ActorConstraintValidator implements ConstraintValidator<ActorConstraint, Actor> {
@Autowired
private ActorModel actorModel;
@Override
public void initialize(ActorConstraint arg0) {
System.out.println("ActorConstraintValidator is initialized");
}
@Override
public boolean isValid(Actor actor, ConstraintValidatorContext context) {
boolean pass = true;
if (getActorModel().isActorExist(actor.getName()) ){
pass = false;
}
return pass;
}
public ActorModel getActorModel() {
return actorModel;
}
public void setActorModel(ActorModel actorModel) {
this.actorModel = actorModel;
}
}
test.entity.Actor
@Entity /*(findByName named query definition is omitted)*/
public class Actor implements Serializable {
public static final String NAMED_QUERY__FIND_ACTOR_BY_NAME = "findActorByName";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ActorConstraint
@NotEmpty
private String name;
@DateTimeFormat(iso=ISO.DATE)
private Date birthday;
@Min(0)
@Max(300)
private Integer height;
...
}
extra note, I have added
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
to spring xml
You put the @ActorConstraint
to the field name
which is of type String
, while the validator type ActorConstraintValidator
is parametrized with Actor
. That is, there is no validator for the @ActorConstraint
constraint and type String
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With