3

I have the following method in my controller:

@PostMapping("/register")
    public String registerNewUser(@Valid User user, BindingResult result, Model model, RedirectAttributes redirectAttributes) {
        System.out.println(result);
        System.out.println(user);
        if(result.hasErrors()) {
            System.out.println("***ERROR***");
            System.out.println(result.getAllErrors());
            return result.getAllErrors().toString();
        } else {
            //userRepository.save(user);
            System.out.println("user saved!");
            return "user saved!";
        }
    }

And my user entity specifies:

@NonNull
@Column(nullable = false, unique = true)
@Valid
public String alias;

Now if I make a simple post request (I use the Advanced REST client for chrome extension) I get:

org.springframework.validation.BeanPropertyBindingResult: 0 errors
User(id=null, email=null, password=null, enabled=false, firstName=null, lastName=null, fullName=null null, alias=null, roles=[], links=[])
user saved!

Where it seems to validate despite @NonNull alias being null.

If I change @NonNull to @NotEmpty

Then validation works as expected:

[Field error in object 'user' on field 'alias': rejected value [null]; codes [NotEmpty.user.alias,NotEmpty.alias,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.alias,alias]; arguments []; default message [alias]]; default message [must not be empty]]

BUT what I don't understand is why @NonNull allows Nulls?

Andronicus
  • 25,419
  • 17
  • 47
  • 88
MrD
  • 4,986
  • 11
  • 48
  • 90

3 Answers3

3

There's no @NonNull annotation in the JSR-303 validation API. The annotation is called @NotNull. Make sure you actually use the javax.validation.constraints.NotNull annotation to mark the field.

Forketyfork
  • 7,416
  • 1
  • 26
  • 33
2

You should use NotNull from javax.validation package and not from lombok (those are to be deleted, when java starts supporting validation - see here). It validates the beans. More info here. You can also use hibernate's @NotNull from org.hibernate.validator. This also does validation.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
2

javax.validation.constraints


@NotNull: The annotated element must not be null.Accepts any type

@NotEmpty: The annotated element must not be null nor empty. Supported types are:

  • CharSequence (length of character sequence is evaluated)
  • Collection (collection size is evaluated)
  • Map (map size is evaluated)
  • Array (array length is evaluated)

@NotBlank:The annotated element must not be null and must contain at least one non-whitespace character. Accepts CharSequence


@NonNull refer to Lombok

Here are the Great Details which you may like Click Here

Romil Patel
  • 12,879
  • 7
  • 47
  • 76