0

I would like to know if there is a better way then writting a check at the beginning of a method.

This question is based on the following code:

Class Pojo:

data class PojoX(val name: String?, val city: String?)

Controller:

@PatchMapping("/demo")
fun update(@RequestBody request: PojoX): PojoDTO{

    if (request.name == null && request.city == null) {
        throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Atleast one field should be filled")
    }

    // Do somthing if atleast one field is filled...
}

I want the code to be maintainable easily without adding new check when a new property is added to the request class.

Is there an annotation in Spring which can check if all fields are null?

Nicktar
  • 5,548
  • 1
  • 28
  • 43
J. Adam
  • 1,457
  • 3
  • 20
  • 38
  • Add `@NotNull` and put `@Valid` next to `@RequestBody`. – M. Deinum Jan 14 '20 at 10:21
  • @M.Deinum I don't want to check on field level, since they are nullable. I just want them not all to be empty/null. So as far i understand NotNull annotation will not help here or am i wrong? – J. Adam Jan 14 '20 at 10:26
  • Then write a rule using javax.validqation. However you will need to add fields to it if you extend it. Unless you start using introspection/reflection... – M. Deinum Jan 14 '20 at 10:29

1 Answers1

0

You'd need to write a custom Validator that is only valid if at least one of the fields is not null (i.e. encapsulating your current check into a validator and then use the @Valid annotation.

Nicktar
  • 5,548
  • 1
  • 28
  • 43