0
0
Spring Bootframework~5 mins

@NotNull, @NotBlank, @NotEmpty in Spring Boot

Choose your learning style9 modes available
Introduction

These annotations help check if data is missing or empty before saving or using it. They keep your app safe and correct.

When you want to make sure a user fills in a form field before submitting.
When saving data to a database and you need certain fields to always have values.
When validating API request data to avoid errors caused by missing or empty inputs.
When you want to give clear error messages if required data is missing.
When you want to avoid null or empty values causing bugs later in your code.
Syntax
Spring Boot
@NotNull
@NotEmpty
@NotBlank

@NotNull means the value cannot be null but can be empty if it is a string or collection.

@NotEmpty means the value cannot be null or empty (like an empty string or empty list).

@NotBlank means the value cannot be null, empty, or only spaces (only for strings).

Examples
This means age cannot be null but can be zero.
Spring Boot
@NotNull
private Integer age;
This means tags cannot be null or an empty list.
Spring Boot
@NotEmpty
private List<String> tags;
This means name cannot be null, empty, or just spaces.
Spring Boot
@NotBlank
private String name;
Sample Program

This class uses the three annotations to make sure the user has an ID, roles list, and username filled properly. The main method shows creating a user and printing the values.

Spring Boot
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;

public class User {

    @NotNull
    private Integer id;

    @NotEmpty
    private List<String> roles;

    @NotBlank
    private String username;

    // Constructor
    public User(Integer id, List<String> roles, String username) {
        this.id = id;
        this.roles = roles;
        this.username = username;
    }

    // Getters
    public Integer getId() { return id; }
    public List<String> getRoles() { return roles; }
    public String getUsername() { return username; }

    public static void main(String[] args) {
        // Example usage
        User user = new User(1, List.of("admin", "user"), "john_doe");
        System.out.println("User ID: " + user.getId());
        System.out.println("Roles: " + user.getRoles());
        System.out.println("Username: " + user.getUsername());
    }
}
OutputSuccess
Important Notes

These annotations work with Spring Boot's validation system and need a validator to check them at runtime.

@NotBlank only works on strings, so use @NotEmpty for collections or arrays.

Use these annotations on fields or method parameters to automatically validate input data.

Summary

@NotNull means value cannot be null but can be empty.

@NotEmpty means value cannot be null or empty (strings, collections).

@NotBlank means value cannot be null, empty, or spaces (only strings).