Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@valid annotation is not working as expected

I am calling an API with the array of objects in the request payload, I have added @valid annotation along the @RequestBody to check if any null properties are sending in my payload. I am expecting if any null data i'm sending it should throw an error. But My code is not throwing an error

Below is my Entity Class

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@DynamicUpdate
@Entity
@Table(name = "student")
public class Student {

   @Id
   @Column(name = "student_id")
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Integer studentId;

   @NotNull
   @Column(name = "name")
   private String name;

   @NotNull
   @Column(name = "gender")
   private String gender;

}

This is my Controller Class

@RestController
@CrossOrigin
public class StudentController {

   @PostMapping("/class/{classId}/student")
   public Student addStudent(@PathVariable Integer classId,@Valid @RequestBody List<Student>  
           student) {

     // My logic Comes Here
     return Student;
    }
  }

Dependency for Validation

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

My Request Payload

[{
   "name":"kiran",
   "gender":"male"
 },
 {
    "name":"divya"
 } 
]

When i send the above payload, i expect an error need to thrown, because i'm not sending gender which is not null, But spring is not throwing any error.

Do i miss something for @valid to work .

like image 585
karthikmunna Avatar asked Nov 15 '25 21:11

karthikmunna


1 Answers

if you use Spring boot 2.3.3.RELEASE. then add in the POM the following dependency:

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

Example of use:

//update audTipo
@PutMapping("audTipo/{id}")
public ResponseEntity<AudTipo> update(@PathVariable(value="id") Integer audTipoId, 
        @Valid @RequestBody AudTipo audTipoDetils) throws ResourceNotFundException
{   
    
      AudTipo audTipo = audTipoRepository.findById(audTipoId).orElseThrow(()-> new
      ResourceNotFundException("NF " + audTipoId));
      audTipo.setXdesc(audTipoDetils.getXdesc());
      
      return ResponseEntity.ok(this.audTipoRepository.save(audTipo));    
}
like image 102
Lusmilo Campos Avatar answered Nov 18 '25 13:11

Lusmilo Campos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!