Hibernate doesn't allow nullable foreign key in OneToMany relationship

Viewed 49

I'm trying to make a foreign key nullable using JPA.

I have two entities with a OneToMany relationship:

@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;

}

I want to be able to save a PersonEntity with a null CompanyEntity.

But when I try

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

Hibernate complains about my entity having a null company_id:

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

When I check the SQL generated by Hibernate for this column, I see it indeed as a NOT NULL constraint:

alter table person_entity
    add company_id serial not null;

How can I make company_id nullable in the relation PersonEntity ?

Edit:

I use Hibernate with PostgreSQLDialect

0 Answers
Related