this is more a theoretical question than technical.I am wondering what is the best way to implement some method(or methods ?) to work on different POJOs that extend the same POJO. In the sample app that I created I want to validate with jakarta some POJO. Here you can find the complete sample app zoo repo, anyway i will describe the main feature here.
I am focusing on a SpringBoot app.
I have a rest controller that accepts as input a List:
@RestController
@RequestMapping(value = "/api/v1", produces = MediaType.APPLICATION_JSON_VALUE)
public class AnimalController {
AnimalService service;
@PostMapping("/validate")
@ResponseStatus(value = HttpStatus.OK)
public List<ValidationErrorDTO> validateCollection(@RequestBody List<AnimalDTO> request)
{
return service.validateCollection(request);
}
public AnimalController(AnimalService service) {
super();
this.service = service;
}
}
In the AnimalDTO class i added some jakarta annotation on the properties and in the method implementation of the service I get the errors:
@Component
public class AnimalServiceImpl implements AnimalService{
@Override
public List<ValidationErrorDTO> validateCollection(List<AnimalDTO> collection) {
List<ValidationErrorDTO> validationErrorList = new ArrayList<>();
//instantiate the validator
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
//for every record of the collection, validate the record and add errors to the error list
for(int i= 0; i<collection.size();i++) {
int k =i;
//get single record errors
Set<ConstraintViolation<AnimalDTO>> violations = validator.validate(collection.get(i));
violations.forEach(v -> validationErrorList.add(new ValidationErrorDTO(k, v.getPropertyPath().toString(), v.getMessage())));
}
return validationErrorList;
}
}
Now, I have two POJOs DogDTO and CatDTO that extend AnimalDTO and i would like to reuse the same method, or anyway apply the best pattern in this scenario, to validate the input list.
What are my options?
I did not to try any coding since this is not a tech issue but I am convinced i'm missing something. Maybe I am overthinking and the best way is just to use another method?
Aucun commentaire:
Enregistrer un commentaire