Home > Back-end >  Problem with @NotNull annotation it's definitely ignoring
Problem with @NotNull annotation it's definitely ignoring

Time:07-23

I have dto class with validation field and when I sending the request I expect Exception with validation error but I got code 201. I added dependency javax.validation and a @Valid annotation before @RequestBody. I exhausted ideas how to solve it Bellow I added my dto class and Contoller class

dto:

import javax.validation.constraints.NotBlank;
import lombok.Data;

@Data
public class AddressDto {
  
  @NotBlank(message = "The country is required.")
  private String country;

  @NotBlank(message = "The city is required.")
  private String city;

  @NotBlank(message = "The Zip code is required.")
  private String zipCode;

  @NotBlank(message = "The street name is required.")
  private String street;

  private String state;
}

controller:

package com.controller;

import com.model.dto.AddressDto;
import javax.validation.Valid;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
public class AddressController {

  @PostMapping("/test")
  public ResponseEntity<AddressDto> registerUser(@Valid @RequestBody AddressDto registerUserDto) {
    return new ResponseEntity<>(registerUserDto, HttpStatus.CREATED);
  }
}

request and response from postman REQUEST&RESPONSEPOSTMAN

CodePudding user response:

Since Spring Boot 2.3 you explicitly need to add a dependency on spring-boot-starter-validation:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

CodePudding user response:

Try to use @JsonInclude(Include.NON_NULL) on the Dto

@JsonInclude(Include.NON_NULL)
public class AddressDto {...}
  • Related