From 7114aed4ed9cb1c0070fbd3ce154f7031a3c51fa Mon Sep 17 00:00:00 2001 From: Gavin Date: Sat, 13 May 2023 11:44:57 +0200 Subject: [PATCH] use Validator for @NotNull --- .../src/main/asciidoc/introduction/Entities.adoc | 9 ++++++++- .../asciidoc/introduction/Hibernate_Introduction.adoc | 8 ++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/documentation/src/main/asciidoc/introduction/Entities.adoc b/documentation/src/main/asciidoc/introduction/Entities.adoc index f3dbfc7d15..cb0b6da0c8 100644 --- a/documentation/src/main/asciidoc/introduction/Entities.adoc +++ b/documentation/src/main/asciidoc/introduction/Entities.adoc @@ -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]] diff --git a/documentation/src/main/asciidoc/introduction/Hibernate_Introduction.adoc b/documentation/src/main/asciidoc/introduction/Hibernate_Introduction.adoc index 574a806d2b..0561793002 100644 --- a/documentation/src/main/asciidoc/introduction/Hibernate_Introduction.adoc +++ b/documentation/src/main/asciidoc/introduction/Hibernate_Introduction.adoc @@ -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() {}