Hibernate forces foreign key to be non-null

  Kiến thức lập trình

I want a Product to have an optional ProductType.
But during schema generation, Hibernate for some reason ignores my definition and creates a non-nullable column for a foreign-key.
We are using Hibernate for schema management and MSSQL Server 16.

This is what Hibernate logs out during schema creation:

create table my_product (id uniqueidentifier not null, name varchar(255) not null, typeId uniqueidentifier not null, primary key (id))
create table my_producttype (id uniqueidentifier not null, name varchar(255) not null, primary key (id))
alter table pg_product add constraint FK123456789 foreign key (typeId) references my_producttype

This is the schema as defined in Java:

@Entity
@Table(name = "my_product")
public class Product extends CoreModel<Product> {

    @NotNull
    private String name;

    @ManyToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
    @JoinColumn(name = "typeId", nullable = true)
    @JsonIgnore
    @org.springframework.lang.Nullable
    private ProductType productType;
}

and this abstract model class

@MappedSuperclass
public abstract class CoreModel<T extends CoreModel<T>> {

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    @Column(updatable = false)
    @GeneratedValue(strategy = GenerationType.UUID)
    @Id
    private UUID id;
}

and finally the referenced entity

@Entity
@Table(name = "my_producttype")
public class ProductType extends CoreModel<ProductType> {


    @NotNull
    private String name;
}

What I tried:

  • using a different nullable annotation (from Spring/Java/Jakarta)
  • checking that I setup the @ManyToOne correctly (see Hibernate not respecting nullable=true in @JoinColumn annotation)

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT