Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null Version fields in JPA?

Nothing in http://docs.oracle.com/javaee/6/api/javax/persistence/Version.html says it cannot be null.

After running

import javax.validation.Validation;
import javax.validation.Validator;

import org.junit.Test;

import static org.junit.Assert.assertFalse;

public class Test
{
    @Test
    public void test()
    {
        //Using Hibernate Validator 4.1.0.Final...
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        assertFalse(validator.validate(new Foo()).isEmpty()); //why does this fail??
    }
}

where Foo.class is simply

import javax.persistence.Entity;
import javax.persistence.Version;

@Entity 
public class Foo
{
    @Version
    private final Integer version = null;
}

the test fails and no @Version validation errors are reported.

So does this mean @Version-annotated fields can be null?

like image 842
ManRow Avatar asked Jan 14 '23 13:01

ManRow


1 Answers

@Version just defines that a particular field is used for optimistic locking. It does not affect the column in DB itself nor the validation. So if you want to enforce not null values you have to use other annotations.

If you leave the version field as null you will get an exception while trying to perform update.

like image 87
Mateusz Mrozewski Avatar answered Jan 17 '23 05:01

Mateusz Mrozewski