JPA bean 验证使用字段还是 属性 访问?

JPA bean validation use field or property access?

JPA bean 验证使用字段还是属性 访问?它应该对 JPA 和验证使用相同的访问类型。如何告诉验证提供者应该使用哪一个?

public class Foo {

    @NotNull
    private String name;

    @Size(20)
    public String getName() {

    }

}

Bean Validation 约束可以在字段和 属性 getter 上。然而,该规范建议仅使用一种访问策略,并且在使用 JPA 时使用用于持久性的相同访问策略。

这是 Bean 验证规范的相关部分(请参阅第 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.