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 (1)
@NotNull: “I just don’t want null, do whatever else you want 😌”
@notblank: “No empty drama either, bring real content 😤”
@column(nullable = false): “I don’t care what you validated… if it’s null, you’re not getting in 😎”
Spring Boot devs learning this the hard way at 2 AM 😅