Home > Blockchain >  @NotNull not working on nested object properties in a Kotlin class even though @Valid is added
@NotNull not working on nested object properties in a Kotlin class even though @Valid is added

Time:07-01

I have a spring-boot app in Kotlin. I have a model called MyModel with just two field : a, b

NotNull validation works fine on a but it doesn't work on b although I've added @valid on top of b.

So when I don't pass b in my api request, it doesn't invalidate the model, although it's invalid (since b is missing).

I really don't know why it doesn't work. if I remove ? to enforce not nullness, then Jackson would throw exception when trying to deserializing the model. So I cannot make it nun-nullable (by removing ? from b). Here is my model.

data class MyModel(

@NotNull(message = "a is mandatory")
lateinit var a: String

@Valid
@NotNull(message = "b is mandatory")
var b: MyNestedModel?
)

data class MyNestedModel(
    @NotNull(message = "MyNestedModel.a is mandatory")
    var a: Date,
    @NotNull(message = "MyNestedModel.b is mandatory")
    var b: String,
    @NotNull(message = "MyNestedModel.c is mandatory")
    var c: String

)

And here is the my controller code :

@RestController
class MyController {
    @Autowired
    lateinit var validator: Validator
    @PostMapping("/aa")
    fun sortingRequest(@RequestBody req: MyModel): ResponseEntity<Any> {
        val validationResult = validator.validate(req)
        return if (validationResult.isEmpty()) {
            ResponseEntity<Any>(null, HttpStatus.CREATED)
        } else {
            ResponseEntity<Any>(HttpErrorResponse("Bad input parameter", validationResult.map {
                it.messageTemplate
            }), HttpStatus.CREATED)
        }
    }
}

Any help would be greatly appreciated.

CodePudding user response:

If you want to have it nullable on the class level and just not allow the nullability from an annotation perspective, I would recommend using @RequestEntity instead of @RequestBody and parse the request body that way. This way you can leave you class non-nullable and handle the parsing error that Jackson throws gracefully if no b is supplied.

CodePudding user response:

I had something similar recently, which was caused by forgetting to include the validator library in my dependencies. The annotations were there, but they were just completely ignored.

This may not be applicable in your situation, but I fixed it by including this into my Gradle file:

implementation("org.springframework.boot:spring-boot-starter-validation")
  • Related