将@Pattern与Float字段一起使用

时间:2015-01-09 00:07:03

标签: java spring validation

在我目前的春季项目中,我尝试使用Float字段从javax.validation.constraints中获取注释模式,这样:

@Pattern(regexp = "[0-9]{2}.[0-9]{2}")
private Float preco;

但是当尝试使用此字段插入或更新实体时,我收到此错误:

Caused by: javax.validation.UnexpectedTypeException: HV000030: No validator could be found for type: java.lang.Float.
        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.verifyResolveWasUnique(ConstraintValidatorManager.java:218)
        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.findMatchingValidatorClass(ConstraintValidatorManager.java:193)
        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.getInitializedValidator(ConstraintValidatorManager.java:97)
        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:125)
        at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:91)
        at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:83)
        at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:547)
        at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:487)
        at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:451)
        at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:403)
        at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:206)
        at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:137)
        at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:95)
        at org.hibernate.action.internal.EntityInsertAction.preInsert(EntityInsertAction.java:218)
        at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:97)
        at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
        at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
        at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
        at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
        at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
        at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
        at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
        at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
        at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:77)

我尝试将此添加到我的项目中:

@Component
public class FloatEditor extends PropertyEditorSupport {
  @Override
  public void setAsText(String text) {
    if (!text.isEmpty()) {
      Float numero = Float.parseFloat(text);
      setValue(numero);
    }
  }
}

并将此行添加到我的控制器的intiBinder方法中:

binder.registerCustomEditor(Float.class, new FloatEditor());

但同样的错误发生了。任何人都知道如何使这项工作?

1 个答案:

答案 0 :(得分:5)

@Pattern注释不能用于验证Float。您需要创建自定义验证器。请找到以下代码:

自定义验证程序注释:

@Target({ METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = FloatValidator.class)
@Documented
public @interface FloatPattern {

    String message() default "Float contraint voilated";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

验证器类:(我没有添加regualr表达式检查,它只是检查简单验证。但是,它可以扩展为进行任何类型的验证)

public class FloatValidator implements ConstraintValidator<FloatPattern, Float> {

    @Override
    public void initialize(final FloatPattern constraintAnnotation) {

    }

    @Override
    public boolean isValid(final Float value,
            final ConstraintValidatorContext context) {
        return value > 11.11;
    }
}

使用此批注的示例类

public class Sample {

    @FloatPattern
    Float preco;

}

测试类

Sample test = new Sample();
test.preco = 11.12f;

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Sample>> violations = validator.validate(test);

for (final ConstraintViolation<Sample> cons : violations) {
        System.out.println(cons.getMessage());
}

输出:(因为验证失败)

Float contraint voilated