How to create an Annotation to validate data from a DTO in Java?

Asked

Viewed 587 times

0

I have a class of a DTO object that I receive in my control through a request using REST. See an example of a request using the verb Post:

@PostMapping
public ResponseEntity<ExibeDisciplinaDto> insere(@RequestBody InsereDisciplinaDto model) {
    validator.isNaoPodeInserir(model);
    var disciplinaInserida = service.insere(model);
    return new ResponseEntity<>(disciplinaInserida, HttpStatus.OK);
}

Currently, my Validator is a @Component, which is called Disciplinavalidation. And within the method, I call the isNaoPodeInserir(model) method passing as parameter my DTO model, the imprint of verifying the integrity of my data I’m receiving in the request.

In Nestjs I managed to make an easy resource using the Typescript language, and I wonder, if here in Java (I’m new) I can perform this task, that can perform the validation through a @Annotation? Here’s an example of how I imagine:

@PostMapping
@DataValidation(DisciplinaValidation.class)
public ResponseEntity<ExibeDisciplinaDto> insere(@RequestBody InsereDisciplinaDto 
    var disciplinaInserida = service.insere(model);
    return new ResponseEntity<>(disciplinaInserida, HttpStatus.OK);
}
  • 1

    What kind of validation you need/want to do in your DTO?

  • Come on, bro! As an example, the DTO has fields of a form, and inside this validation class, I make validations like: text size, if an object or text is null, I check the restrictions of existence of a certain entity in the database, among other things. Generally, return a boolean or work in issuing exceptions...

  • 1

    I think this here can help you

  • I am extremely grateful for your collaboration. I’ve also seen this documentation before. It’s cool! But it’s almost that, it’s not yet the solution to this problem. These validations could be within my DTO class. But, I would call this class in the signature of my method that receives external requests. For example: @DataValidation(DisciplinaValidation.class). Within Disciplinavalidation, I could have Bean Validation validations. But Annotation Datavalidation is who would call these validations.

  • 1

    Why don’t you create a "Service" with its validations? If you need to reuse it, you can create a "Validacoesutils" and call it.

  • @Rafaelbarbosa I currently have this, but subsequently I did a schematic in C# where I create this service and pass on an annotation. For example: @Validator(Servvalidator.class), and this is the parameters being passed in the method.

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.