use Validator for @NotNull

This commit is contained in:
Gavin 2023-05-13 11:44:57 +02:00 committed by Christian Beikov
parent 6d398db1fa
commit 7114aed4ed
2 changed files with 14 additions and 3 deletions

View File

@ -554,6 +554,12 @@ Note that primitively-typed attributes are inferred `NOT NULL` by default.
String middleName; // may be null
----
[TIP]
====
An even better solution is to use the `@NotNull` annotation from Bean Validation.
Just add Hibernate Validator to your project build.
====
.Should I use `optional=false` or `nullable=false` in JPA?
****
There are two ways to mark a mapped column `not null` in JPA:
@ -577,7 +583,8 @@ Note that:
- `optional=false` implies `nullable=false`, but
- `nullable=false` _does not_ imply `optional=false`.
Therefore, we recommend `@Basic(optional=false)` in preference to `@Column(nullable=false)` in most circumstances.
Therefore, we prefer `@Basic(optional=false)` to `@Column(nullable=false)`.
But the `@NotNull` annotation from Bean Validation is even nicer.
****
[[enums]]

View File

@ -227,6 +227,10 @@ dependencies {
// the GOAT ORM
implementation 'org.hibernate.orm:hibernate-core:6.2.2.Final'
// Hibernate Validator
implementation 'org.hibernate.validator:hibernate-validator:8.0.0.Final'
implementation 'org.glassfish:jakarta.el:4.0.2'
// Agroal connection pool
implementation 'org.hibernate.orm:hibernate-agroal:6.2.2.Final'
implementation 'io.agroal:agroal-pool:2.1'
@ -270,16 +274,16 @@ We begin with our _entity class_:
----
package org.hibernate.example;
import jakarta.persistence.Basic;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.validation.constraints.NotNull;
@Entity
class Book {
@Id
String isbn;
@Basic(optional = false)
@NotNull
String title;
Book() {}