DEV Community

Babisha S
Babisha S

Posted on

@NotBlank vs @Column(nullable = false) vs @NotNull — Which one should you use?

When I started working with Spring Boot, I thought all three did the same thing.

They don’t.

Understanding the difference between them helped me write cleaner and safer backend code.

1. @NotNull

  • Prevents null
  • Allow empty string "" and spaces " ".
  • Provided by Hibernate Validator, used for application level validation.
  • Works both for string and integer.

2. @NotBlank

  • Prevents null, empty string "" and spaces " ".
  • Provided by Bean Validation API(Hibernate Validator), used for application level validation.
  • Works only for string.

3. @Column(nullable = false)

  • This is not validation. It is database constraint.
  • Prevents null
  • Allow empty string "" and spaces " ".
  • Provided by JPA, used for database level constraints.

Which is better?

Use both @NotBlank and @Column(nullable = false) for string to ensure data integrity at both levels. Use @NotNull if just presence of value is enough.

Top comments (0)