Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation

1. Overview

Bean Validation is a standard validation specification that allows us to easily validate domain objects by using a set of constraints declared in the form of annotations.

While overall, the use of bean validation implementations such as Hibernate Validator is fairly straightforward, it’s worth exploring some subtle — yet relevant — differences regarding how some of these constraints are implemented.

In this tutorial, we’ll spot the differences between the @NotNull, @NotEmpty, and @NotBlank constraints.

2. The Maven Dependencies

To quickly set up a working environment and test the behavior of the @NotNull, @NotEmpty, and @NotBlank constraints, first we need to add the required Maven dependencies.

In this case, we’ll use Hibernate Validator, the bean validation reference implementation, for validating our domain objects.

Here’s the relevant section of our pom.xml file:

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.13.Final</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.el</artifactId>
        <version>3.0.0</version>
     </dependency>
</dependencies>

We’ll use JUnit and AssertJ in our unit tests, so make sure to check the latest versions of hibernate-validator, GlassFish’s EL implementation, junit, and assertj-core on Maven Central.

[[the-@notnull-constraint]]
=== 3. The @NotNull Constraint

[[the-@notnull-constraint]]Moving forward, let’s implement a naive UserNotNull domain class and constrain its name field with the @NotNull annotation:

public class UserNotNull {

    @NotNull(message = "Name may not be null")
    private String name;

    // standard constructors / getters / toString
}

Now, we need to see how @NotNull actually works under the hood

To do so, let’s create a simple unit test for the class and validate a few instances of it:

@BeforeClass
public static void setupValidatorInstance() {
    validator = Validation.buildDefaultValidatorFactory().getValidator();
}

@Test
public void whenNotNullName_thenNoConstraintViolations() {
    UserNotNull user = new UserNotNull("John");
    Set<ConstraintViolation<UserNotNull>> violations = validator.validate(user);

    assertThat(violations.size()).isEqualTo(0);
}

@Test
public void whenNullName_thenOneConstraintViolation() {
    UserNotNull user = new UserNotNull(null);
    Set<ConstraintViolation<UserNotNull>> violations = validator.validate(user);

    assertThat(violations.size()).isEqualTo(1);
}

@Test
public void whenEmptyName_thenNoConstraintViolations() {
    UserNotNull user = new UserNotNull("");
    Set<ConstraintViolation<UserNotNull>> violations = validator.validate(user);

    assertThat(violations.size()).isEqualTo(0);
}

As expected, the @NotNull constraint won’t allow null values for the constrained field(s). Even so, the field(s) can be empty.

To better understand this, let’s look at the NotNullValidator classisValid() method, which the @NotNull constraint uses. The method implementation is really trivial:

public boolean isValid(Object object) {
    return object != null;
}

As shown above, a field (e.g. CharSequence, Collection, Map, or Array) constrained with @NotNull must be not null. An empty value, however, is perfectly legal.

[[the-@notempty-constraint]]
=== 4. The @NotEmpty Constraint

[[the-@notempty-constraint]]Now, let’s implement a sample UserNotEmpty class and use the @NotEmpty constraint:

public class UserNotEmpty {

    @NotEmpty(message = "Name may not be empty")
    private String name;

    // standard constructors / getters / toString
}

With the class in place, let’s just test it by assigning different values to the name field:

@Test
public void whenNotEmptyName_thenNoConstraintViolations() {
    UserNotEmpty user = new UserNotEmpty("John");
    Set<ConstraintViolation<UserNotEmpty>> violations = validator.validate(user);

    assertThat(violations.size()).isEqualTo(0);
}

@Test
public void whenEmptyName_thenOneConstraintViolation() {
    UserNotEmpty user = new UserNotEmpty("");
    Set<ConstraintViolation<UserNotEmpty>> violations = validator.validate(user);

    assertThat(violations.size()).isEqualTo(1);
}

@Test
public void whenNullName_thenOneConstraintViolation() {
    UserNotEmpty user = new UserNotEmpty(null);
    Set<ConstraintViolation<UserNotEmpty>> violations = validator.validate(user);

    assertThat(violations.size()).isEqualTo(1);
}

The @NotEmpty annotation makes use of the @NotNull class’ isValid() implementation and additionally checks that the size/length of the supplied object (of course, this varies according to the type of object being validated) is greater than zero.

In a nutshell, this means that a field (e.g. CharSequence, Collection, Map, or Array) constrained with @NotEmpty must be not null and its size/length must be greater than zero.

Additionally, we can be even more restrictive if we use the @NotEmpty annotation in conjunction with @Size.

In doing so, we’d also enforce that the object’s min and max size values are within the specified min/max range:

@NotEmpty(message = "Name may not be empty")
@Size(min = 2, max = 32, message = "Name must be between 2 and 32 characters long")
private String name;

[[the-@notblank-constraint]]
=== 5. The @NotBlank Constraint

[[the-@notblank-constraint]]Similarly, we can constrain a class field with the @NotBlank annotation:

public class UserNotBlank {

    @NotBlank(message = "Name may not be blank")
    private String name;

    // standard constructors / getters / toString

}

Along the same lines, we can implement a unit test to understand how the @NotBlank constraint works:

@Test
public void whenNotBlankName_thenNoConstraintViolations() {
    UserNotBlank user = new UserNotBlank("John");
    Set<ConstraintViolation<UserNotBlank>> violations = validator.validate(user);

    assertThat(violations.size()).isEqualTo(0);
}

@Test
public void whenBlankName_thenOneConstraintViolation() {
    UserNotBlank user = new UserNotBlank(" ");
    Set<ConstraintViolation<UserNotBlank>> violations = validator.validate(user);

    assertThat(violations.size()).isEqualTo(1);
}

@Test
public void whenEmptyName_thenOneConstraintViolation() {
    UserNotBlank user = new UserNotBlank("");
    Set<ConstraintViolation<UserNotBlank>> violations = validator.validate(user);

    assertThat(violations.size()).isEqualTo(1);
}

@Test
public void whenNullName_thenOneConstraintViolation() {
    UserNotBlank user = new UserNotBlank(null);
    Set<ConstraintViolation<UserNotBlank>> violations = validator.validate(user);

    assertThat(violations.size()).isEqualTo(1);
}

The @NotBlank annotation uses the NotBlankValidator class, which checks that a character sequence’s trimmed length is not empty:

public boolean isValid(
  CharSequence charSequence,
  ConstraintValidatorContext constraintValidatorContext)
    if (charSequence == null ) {
        return true;
    }
    return charSequence.toString().trim().length() > 0;
}

Funny enough, the method returns true for null values. So, we might think that @NotBlank does allow null values, but it actually doesn’t.

The @NotNull class’ isValid() method is called after the @NotBlank class’ isValid(), hence forbidding null values.

To put it simply, a String field constrained with @NotBlank must be not null and the trimmed length must be greater than zero.

6. A Side-by-Side Comparison

So far, we’ve taken an in-depth look at how the @NotNull, @NotEmpty, and @NotBlank constraints operate individually on class fields.

Let’s perform a quick side-by-side comparison, so we can have a bird’s eye view of the constraints’ functionality and easily spot their differences:

  • @NotNull: a constrained CharSequence, Collection, Map, or Array is valid as long as it’s not null, but it can be empty

  • @NotEmpty: a constrained CharSequence, Collection, Map, or Array is valid as long as it’s not null and its size/length is greater than zero

  • @NotBlank: a constrained String is valid as long as it’s not null and the trimmed length is greater than zero

7. Conclusion

In this article, we looked at the NotNull, @NotEmpty, and @NotBlank constraints implemented in Bean Validation and highlighted their similarities and differences.

As usual, all the code samples shown in this article are available over on GitHub.

Leave a Reply

Your email address will not be published.