Hibernate 不允许 OneToMany 关系中的可为空的外键

时间:2021-03-09 05:20:29

标签: hibernate jpa

我正在尝试使用 JPA 使外键可以为空。

我有两个具有 OneToMany 关系的实体:

@Entity
public class PersonEntity {

    @Id
    private Long id;

    @JoinColumn(name = "company_id", nullable = true)
    @ManyToOne(optional = true, fetch = FetchType.LAZY)
    private CompanyEntity company;

}


@Entity
public class CompanyEntity {

    @Id
    private Long id;

    @OneToMany(mappedBy = "company")
    private List<PersonEntity > personEntityList;

}

我希望能够使用空 PersonEntity 保存 CompanyEntity

但是当我尝试

PersonEntity john = new PersonEntity();
person.setName("John")
personRepository.save(john)

Hibernate 抱怨我的实体有 null company_id:

org.postgresql.util.PSQLException: ERROR: null value in column "company_id" violates not-null constraint

当我检查 Hibernate 为该列生成的 SQL 时,我确实将其视为 NOT NULL 约束:

alter table person_entity
    add company_id serial not null;

如何使关系 company_id 中的 PersonEntity 可以为空?

编辑:

我将 Hibernate 与 PostgreSQLDialect 一起使用

0 个答案:

没有答案