将@Pattern 与 Float 字段一起使用

using @Pattern with Float field

在我当前的 spring 项目中,我正在尝试使用 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());

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

@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 {};

}

验证器class:(我没有添加正则表达式检查,它只是检查简单的验证。但是,它可以扩展到做任何类型的验证)

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;
    }
}

示例 class 使用此注释

public class Sample {

    @FloatPattern
    Float preco;

}

测试class

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