Optional containing a list of items is not being validated
As a user of Hibernate Validator, I would expect that a field like
where ConsumerGroupDTO is the following pojo:
gets properly validated and constraint violation exception will be thrown in case consumerGroupId value will be set either to null or an empty string, instead validation does not kick-in for the list of pojos wrapped in the Optional.
If the value of Optional is a pojo or a primitive, validation rules are working fine.
I did a little bit more digging and tried to write my own value extractor:
but when I register this class as a service, I get an exception with the cause:
It seems it doesn't like that I have a class type specified in my Optional. But without this generic, it is impossible to have the extractor working the right way.
Anyways, I think it is either a bug in HV or a functional deficiency.
Looking forward to your reply!
I will be logging a bug against spring-beans project then, thanks for the clarification!
Well, I have no idea what Spring is doing. I know it would work with vanilla Hibernate Validator.
Apparently, you have a Spring exception, not an Hibernate Validator one.
Ok, but even if I add @Valid in front of the dto, I am getting:
org.springframework.beans.InvalidPropertyException: Invalid property 'consumerGroups' of bean class [...ApplicationDTO]: Illegal attempt to get property 'consumerGroups' threw exception; nested exception is org.springframework.beans.InvalidPropertyException: Invalid property 'consumerGroups' of bean class [...ApplicationDTO]: Property referenced in indexed property path 'consumerGroups' is neither an array nor a List nor a Set nor a Map; returned value was [Optional[[ConsumerGroupDTO(consumerGroupId=, simpleConsumerGroup=false)]]]
This seems like a bug, it doesn’t generate a proper constraint violation.
It should be supported out of the box if you enable cascaded validation: