I am trying to validate Employee Request and the validations should be different for post method,put method and delete method
public class Employee {
@NotNull(message = "Employee Id can not be null")
private Integer id;
@Min(value = 2000, message = "Salary can not be less than 2000")
@Max(value = 50000, message = "Salary can not be greater than 50000")
private Integer salary;
@NotNull(message = "designation can not be null")
private String designation;
}
For post method want to validate all the fields present in the request
@PostMapping("/employees")
public ResponseEntity<Void> addEmployee(@Valid @RequestBody Employee newEmployee) {
Employee emp= service.addEmployee(newEmployee);
if (emp== null) {
return ResponseEntity.noContent().build();
}
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
Для моего метода put я хочу проверить только поле Salary, а остальные поля не будут проверяться
@PutMapping("/employees/{id}")
public ResponseEntity<Vehicle> updateEmployee(@Valid @RequestBody Employee updateEmployee) {
Employee emp= service.EmployeeById(updateEmployee.getId());
if (null == emp) {
return new ResponseEntity<Employee>(HttpStatus.NOT_FOUND);
}
emp.setSalary(updateEmployee.getSalary());
emp.setDesignation(updateEmployee.getDesignation());
service.updateEmployee(emp);
return new ResponseEntity<Employee>(emp, HttpStatus.OK);
}
Для удаления я не хочу выполнять какую-либо проверку
@DeleteMapping("/employees/{id}")
public ResponseEntity<Employee> deleteEmployee(@Valid @PathVariable int id) {
Employee emp = service.getEmployeeById(id);
if (null == employee) {
return new ResponseEntity<Employee>(HttpStatus.FOUND);
}
service.deleteEmployee(id);
return new ResponseEntity<Employee>(HttpStatus.NO_CONTENT);
}
Но если я использую @Valid, все методы проверяются со всеми полями.