Database schema validation & primitive nullables

Hey,

I have a Spring project (Hibernate 6.6) with database schema validation enabled with spring.jpa.hibernate.ddl-auto=validate. I have a simple test entity:

@Entity
public class TestEntity {
  @Id int id;
  int number;
  // Getters & setters...
}

And my schema is as follows with some test data:

CREATE TABLE test_entity (
    id INT PRIMARY KEY NOT NULL,
    number INT
);

INSERT INTO test_entity VALUES (1, 1);
INSERT INTO test_entity VALUES (2, NULL);

Hibernate validation passes even though number is a primitive field that maps to a nullable column. When annotating the field with @Column(nullable = false) validation still passes.

Perhaps I’m missing something or is this a missing feature? I would find primitive ↔ nullable validation very useful so it’s more difficult to create footguns (ask me how I know :sweat_smile:). Feels especially strange since letting Hibernate create the table with spring.jpa.hibernate.ddl-auto=create sets the number column as non-nullable.

Apologies if this has been discussed before, I couldn’t find information about this particular topic.

You can watch and vote on the Hibernate issue for strict validation. Schema validation so far is a tool to verify if the schema that you have is compatible to the schema that Hibernate ORM would produce. Obviously, a nullability constraint is not necessarily important as long as the data does not contain a null. Similarly, a missing nullable = false config on the Hibernate mapping side when you have a not-null constraint on your database shouldn’t be a big deal, because the error would be caught by the database ultimately.

If you want to diff your schema against Hibernate ORM expectations to understand if you need a migration, you should look into tools like Liquibase. Quarkus has great integrations with that tool that allow to generate change sets/logs quite easily.

1 Like