首页 > 解决方案 > 尽管使用了 @Access(value=AccessType.FIELD),但 JPA Hibernate 在 Getter 上使用 @NotNull 注释

问题描述

我有一个使用的实体

@Entity
@Table(
        indexes = {@Index(name="URL_PARAMETER_INDEX", unique = true, columnList = "urlParameter")}
)
@Access(value=AccessType.FIELD)
public class EntityA extends UniqueIdEntity {

    // From @MappedSuperClass "UniqueIdEntity"
    @Id
    @GeneratedValue(generator = "uuid2")
    @Column(unique = true, updatable = false, columnDefinition = "uuid")
    protected UUID id;

    @Column(name = "urlParameter", unique = true, nullable = true)
    private String urlParameter;

    ...

    @javax.validation.constraints.NotNull
    public String getUrlParameter() {
        if(this.urlParameter == null) {
            this.urlParameter = this.calculateUrlParameter();
        }
        return urlParameter;
    }

}

虽然字段 urlParameter 可以为 null,但在第一次访问时会生成它并返回新生成的值,因此该字段可能为 null,但 getter 永远不会返回 null。

但是,JPA 将其转换为以下 DDL 命令:add column url_parameter varchar(255) not null当我删除 getter 上的 @NotNull 注释时,它会将列生成为可为空的。

我究竟做错了什么?我已经@Access(value=AccessType.FIELD)在每个超类上添加了,以确保 JPA/Hibernate 使用正确的访问类型。

如何确保 Column 可以为空,同时在我的 Getter 上仍然有 @NotNull 注释?

标签: javahibernatejpaddl

解决方案


推荐阅读