JPA Not Null Constraint / Not Nullable column

Introduction

This tutorial explains how to make a column not nullable in JPA - a mandatory value that may never be null - on a simple column with @Column(nullable = false), and on a relationship's foreign key with @JoinColumn(nullable = false). It also shows Bean Validation's @NotNull, which is usually the better first line of defence, and what each of them actually does when a null arrives. A program saves six employees against a real database and prints which saves succeed and which fail, and at which point.

(Updated in November 2026 for Jakarta Persistence 3.2, Hibernate 7 and Bean Validation. The earlier version said that unique columns are not nullable by default; that is not the case, and the example below shows it.)

What is a not null constraint

In a database schema, every column is nullable unless it is declared NOT NULL. The one exception is the primary key, which can never be null. A UNIQUE constraint does not make a column mandatory: in most databases, including H2, PostgreSQL, MySQL and Oracle, a unique column accepts any number of nulls, because a null is not considered equal to another null. (SQL Server is the well-known exception: by default it allows a single null in a unique column.) To make a column mandatory, we declare it not nullable, and JPA lets us express the same on the entity.

There are three places to say that a value is required -
  • @Column(nullable = false) on a field: the column is generated as NOT NULL.
  • @JoinColumn(nullable = false) on a relationship: the foreign key column is NOT NULL, so the relationship is required.
  • @NotNull from Bean Validation (jakarta.validation.constraints.NotNull): the value is checked in Java before the entity is saved.

The example

An EMPLOYEE table has a mandatory social security number, a mandatory name, a mandatory parking slot, and an optional but unique badge number. The program runs on Spring Boot with Hibernate and an in-memory H2 database, which creates the tables from the entities; the validation starter is on the classpath, so Bean Validation is active -
ParkingSlot.java
//ParkingSlot.java
package com.javabrahman.jpa.notnull;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class ParkingSlot {
  @Id
  private int parkingSlotId;

  protected ParkingSlot() {
  }

  public ParkingSlot(int parkingSlotId) {
    this.parkingSlotId = parkingSlotId;
  }
}
Employee.java - three ways to say "required", and one unique column
//Employee.java
package com.javabrahman.jpa.notnull;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.validation.constraints.NotNull;

@Entity
public class Employee {
  @Id
  private int employeeId;

  @Column(nullable = false)                       // JPA: NOT NULL in the generated table
  private String socialSecurityNumber;

  @NotNull                                        // Bean Validation: checked before the SQL is sent
  private String name;

  @ManyToOne
  @JoinColumn(name = "PARKING_SLOT_ID", nullable = false)   // a required relationship
  private ParkingSlot parkingSlot;

  @Column(unique = true)                          // unique, but nullable
  private String badgeNumber;

  protected Employee() {
  }

  public Employee(int employeeId, String socialSecurityNumber, String name, ParkingSlot parkingSlot, String badgeNumber) {
    this.employeeId = employeeId;
    this.socialSecurityNumber = socialSecurityNumber;
    this.name = name;
    this.parkingSlot = parkingSlot;
    this.badgeNumber = badgeNumber;
  }
}
NotNullApp.java - saving valid and invalid employees
//NotNullApp.java
package com.javabrahman.jpa.notnull;

import jakarta.persistence.EntityManager;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.support.TransactionTemplate;

@SpringBootApplication
public class NotNullApp {

  @Bean
  CommandLineRunner demo(EntityManager em, TransactionTemplate tx) {
    return args -> {
      tx.executeWithoutResult(s -> em.persist(new ParkingSlot(10)));
      ParkingSlot slot = tx.execute(s -> em.find(ParkingSlot.class, 10));

      save("1. all required values", tx, em, new Employee(1, "123-45-6789", "Ann", slot, "B-001"));
      save("2. no social security number", tx, em, new Employee(2, null, "Raj", slot, "B-002"));
      save("3. no name", tx, em, new Employee(3, "222-33-4444", null, slot, "B-003"));
      save("4. no parking slot", tx, em, new Employee(4, "333-44-5555", "Eve", null, "B-004"));
      save("5. no badge number", tx, em, new Employee(5, "444-55-6666", "Max", slot, null));
      save("6. no badge number again", tx, em, new Employee(6, "555-66-7777", "Lea", slot, null));
      System.out.println("employees saved: " + tx.execute(s -> em.createQuery("select count(e) from Employee e", Long.class).getSingleResult()));
    };
  }

  private static void save(String what, TransactionTemplate tx, EntityManager em, Employee employee) {
    System.out.println("== " + what);
    try {
      tx.executeWithoutResult(s -> em.persist(employee));
      System.out.println("   saved");
    } catch (RuntimeException e) {
      Throwable cause = e;
      while (cause.getCause() != null && cause.getCause() != cause) {
        cause = cause.getCause();
      }
      System.out.println("   " + e.getClass().getSimpleName() + ", caused by " + cause.getClass().getSimpleName());
      System.out.println("   " + cause.getMessage().lines().findFirst().orElse(""));
    }
  }

  public static void main(String[] args) {
    SpringApplication.run(NotNullApp.class, args);
  }
}
 OUTPUT of the above code
Hibernate: drop table if exists employee cascade
Hibernate: drop table if exists parking_slot cascade
Hibernate: create table employee (employee_id integer not null, parking_slot_id integer not null, badge_number varchar(255) unique, name varchar(255) not null, social_security_number varchar(255) not null, primary key (employee_id))
Hibernate: create table parking_slot (parking_slot_id integer not null, primary key (parking_slot_id))
Hibernate: alter table if exists employee add constraint FK1p3pcr65et1ve2qsthsysn7hm foreign key (parking_slot_id) references parking_slot
Hibernate: insert into parking_slot (parking_slot_id) values (?)
Hibernate: select ps1_0.parking_slot_id from parking_slot ps1_0 where ps1_0.parking_slot_id=?
== 1. all required values
Hibernate: select null from parking_slot ps1_0 where ps1_0.parking_slot_id=?
Hibernate: insert into employee (badge_number,name,parking_slot_id,social_security_number,employee_id) values (?,?,?,?,?)
   saved
== 2. no social security number
Hibernate: select null from parking_slot ps1_0 where ps1_0.parking_slot_id=?
Hibernate: insert into employee (badge_number,name,parking_slot_id,social_security_number,employee_id) values (?,?,?,?,?)
   DataIntegrityViolationException, caused by JdbcSQLIntegrityConstraintViolationException
   NULL not allowed for column "SOCIAL_SECURITY_NUMBER"; SQL statement:
== 3. no name
Hibernate: select null from parking_slot ps1_0 where ps1_0.parking_slot_id=?
   TransactionSystemException, caused by ConstraintViolationException
   Validation failed for classes [com.javabrahman.jpa.notnull.Employee] during persist time for groups [jakarta.validation.groups.Default, ]
== 4. no parking slot
Hibernate: insert into employee (badge_number,name,parking_slot_id,social_security_number,employee_id) values (?,?,?,?,?)
   DataIntegrityViolationException, caused by JdbcSQLIntegrityConstraintViolationException
   NULL not allowed for column "PARKING_SLOT_ID"; SQL statement:
== 5. no badge number
Hibernate: select null from parking_slot ps1_0 where ps1_0.parking_slot_id=?
Hibernate: insert into employee (badge_number,name,parking_slot_id,social_security_number,employee_id) values (?,?,?,?,?)
   saved
== 6. no badge number again
Hibernate: select null from parking_slot ps1_0 where ps1_0.parking_slot_id=?
Hibernate: insert into employee (badge_number,name,parking_slot_id,social_security_number,employee_id) values (?,?,?,?,?)
   saved
Hibernate: select count(e1_0.employee_id) from employee e1_0
employees saved: 3
Hibernate: drop table if exists employee cascade
Hibernate: drop table if exists parking_slot cascade

Explanation of the output: the table

The generated employee table shows what each annotation did to the schema: social_security_number varchar(255) not null from @Column(nullable = false), parking_slot_id integer not null from @JoinColumn(nullable = false), and name varchar(255) not null - from @NotNull. Hibernate reads Bean Validation constraints too when it generates the schema, so @NotNull alone produced a NOT NULL column. badge_number varchar(255) unique is unique, and nullable.

Explanation of the output: the saves

  • 1. All values present: saved. (The select null from parking_slot statements are Hibernate checking the parking slot reference before each insert.)
  • 2. No social security number: the insert was sent to the database, which refused it: "NULL not allowed for column SOCIAL_SECURITY_NUMBER". Spring reported it as a DataIntegrityViolationException. @Column(nullable = false) describes the schema; the check itself was made by the database.
  • 3. No name: refused before any SQL - there is no insert in the output - with a Bean Validation ConstraintViolationException, "Validation failed for classes [...Employee] during persist time". Spring wrapped it in a TransactionSystemException because it happened while committing. Bean Validation also produces a clear message per field, which is easier to report to a user than a database error.
  • 4. No parking slot: like case 2, the database refused the insert: "NULL not allowed for column PARKING_SLOT_ID". A required relationship is just a not-null foreign key.
  • 5 and 6. No badge number, twice: both saved, although badge_number is unique. Two nulls in a unique column are allowed, which is why "unique" never means "required". Three employees were saved in the end: 1, 5 and 6.

Which one to use

Summary

In this tutorial we made values mandatory in JPA. @Column(nullable = false) and @JoinColumn(nullable = false) made Hibernate generate NOT NULL columns, and with them a null value was refused by the database when the insert ran. Bean Validation's @NotNull refused a null before any SQL was sent, and also produced a NOT NULL column. A unique column, finally, accepted two nulls: only the primary key and explicitly not-null columns are mandatory.