Search code examples
jpabean-validation

JPA bean validation use field or property access?


JPA bean validation use field or property access? It should use the same access type for both JPA and validation. How to tell validation provider which one should be used?

public class Foo {

    @NotNull
    private String name;

    @Size(20)
    public String getName() {

    }

}

Solution

  • Bean Validation constraints can be on both the field and the property getter. The spec however recommends using only one access strategy, and when using JPA use the same access strategy used for persistence.

    Here is the relevant part of the Bean Validation spec (see section 5.1.2):

    Constraint declarations can be applied on both fields and properties for the same object type. The same constraint should however not be duplicated between a field and its associated property (the constraint validation would be applied twice). It is recommended for objects holding constraint declarations to adhere to a single state access strategy (either annotated fields or properties).

    NOTE Java Persistence and Bean Validation For maximum portability, persistent properties hosting Bean Validation constraints should use the same access strategy used in Java Persistence. In other words, place your Bean Validation constraint annotations on the same element (field or getter) as your Java Persistence annotations.

    When a field is annotated with a constraint declaration, field access strategy is used to access the state validated by such constraint.

    When a property is annotated with a constraint declaration, property access strategy is used to access the state validated by such constraint.