问题
There is the @NotNull
annotation which validates that a certain object is not null.
There is the @NotEmpty
annotation which validates that a certain collection/map/string/... is not empty.
Is there also an annotation which valides that a certain collection/map does not contain any nulls? I am unable to find it. It seems so basic, that I believe it must be in the JSR-303 spec.
回答1:
There is no such built-in constraints. You can easily write your custom constraints, eg @NoNullElements, which does what you want. Refer to the Refer to the documentation http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#validator-customconstraints to see how to write custom constraints.
回答2:
Per the Hibernate 5.2 release announcement, Hibernate Validator 5.2 provides the ability to add validation annotations to the generic type of an Iterable, e.g. List<@MyValidationAnnotation String> myList;
. However, you cannot currently use the existing validation annotations, as they do not have "java.lang.annotation.ElementType.TYPE_USE" in their definition. It sounds like it's still an open question of how or whether Bean Validation 1.2 will support this.
So, in short, if you are using Java 8, and Hibernate as your bean validation library, you can write your own @NotNull validation annotation with TYPE_USE in its definition, and apply it to the generic type of the list. Otherwise, Hardy's answer about writing your own custom constraint to verify that every element of the list is non-null is probably the way to achieve this.
Update:
Bean Validation API from version 2.0 has TYPE_USE
as a target in the validators. So one can easily do List<@NotNull String> stringList
.
回答3:
I had the same Problem. And the only solution I found was, adding a null validation into the setters of the Entity. If the submitted value is null -> return. I know thats pretty ugly but the only way I know how to avoid exceptions.
来源:https://stackoverflow.com/questions/27984137/java-beans-validation-collection-map-does-not-contain-nulls