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 .
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With