Search code examples
hibernate-validator

Hibernate-validator 6: Weird behavior of the @Max annotation with a BigDecimal set on a Number field


I think I might have found an oddity in hibernate-validator 6.0.15.Final. It used to work with the version 5.4.2.Final.

Here is a test example:

import lombok.Data;
import org.junit.Test;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.Max;
import java.math.BigDecimal;
import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;

public class ValidTest {

    @Data
    static class ClassToValidate{

        public ClassToValidate() {
            failingNumber = new BigDecimal("1.001");
            failingBigDecimal = new BigDecimal("1.001");

            passingNumber = new BigDecimal("0.001");
            passingBigDecimal = new BigDecimal("0.001");
        }

        @Max(1)
        private Number failingNumber;

        @Max(1)
        private BigDecimal failingBigDecimal;

        @Max(1)
        private Number passingNumber;

        @Max(1)
        private BigDecimal passingBigDecimal;
    }

    @Test
    public void test(){
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        Set<ConstraintViolation<ClassToValidate>> violations = validator
                .validate(new ClassToValidate());

        for (ConstraintViolation<ClassToValidate> violation : violations) {
            System.out.println(violation);
        }
        assertThat(violations).hasSize(2);
    }

}

The BigDecimal stored in a Number field will not trigger a constraint exception even though it is bigger than 1. And a bigdecimal such as 2.xxx would.

It feels like the validator does not (anymore) take into account the numbers after the comma in BigDecimals objects stored in a Number.


Solution

  • Hum, you're right, we have a bug here: when you use a Number as the declared type as you did, we end up comparing longs. It should be an easy fix though.

    I saw you filled https://hibernate.atlassian.net/browse/HV-1699 , we will give you updates there.

    I will make a release as soon as we have a fix as it's definitely a bad one.