Video in progress
How does `@Column(nullable = false)` differ from Bean Validation's `@NotNull`?
@Column(nullable = false) is mostly for DDL: if Hibernate creates the schema, it puts NOT NULL on the column, and the database does the checking. @NotNull is Java-level validation: Hibernate checks it before persist/update and throws an error before the SQL is even sent.
📖 Answer
Let's look at both side by side:
@Entity
class Customer {
@Column(nullable = false)
private String phone; // DDL: phone varchar(255) not null
@NotNull
private String email; // ConstraintViolationException before the flush
}
For nullable = false to have any effect, the schema must be created by Hibernate. If Flyway manages the schema on prod, this attribute does nothing for DDL (without Bean Validation Hibernate's hibernate.check_nullability throws PropertyValueException on flush; with Bean Validation that check is off), and you write the NOT NULL in the migration yourself. If it's forgotten in the migration too, a null is saved silently.
@NotNull (Jakarta Validation) needs Hibernate Validator on the classpath (spring-boot-starter-validation). Then Hibernate checks it at the pre-persist/pre-update stage and throws jakarta.validation.ConstraintViolationException, which says exactly which field is wrong. That's far clearer than a database error.
One interesting detail: when Hibernate sees @NotNull, it also makes the column NOT NULL during DDL generation (hibernate.validator.apply_to_ddl, on by default). So @NotNull does both jobs.
In practice I use both: @NotNull for a clear error and API validation, and NOT NULL in the migration as the last line of defense, because your application isn't the only thing that writes to the database.
Sign up to mark studied questions and save your progress.