views:

41

answers:

1

I'm using the hibernate implementation of the javax.validation and would like to know how whether anyone has been able to apply the @NotNull constraint annotation to all fields of a class, rather than to each individual field?

I would prefer to enforce the @NotNull constraint as a default across my project, to avoid littering the code with @NotNull annotations on every field. Ideally it would be preferable to define a custom constraint "@MayBeNull" to annotated any fields that may be null.

A: 

Does it really make sense in your case to validate all fields against null? What about for example with basic types like int, long, etc

Anyways, Bean Validation does not offer the functionality you are asking for. You could write a custom class constraint @MyNotNull which via reflection validated all fields against null. Personally I recommend against it.

Hardy
Thanks Hardy. I tried writing a custom validator. While it's possible as you've suggested, I tend to agree now that it's not the most elegant solution. I think that the convenience it adds is not enough of an advantage. A disadvantage of a custom validation at class level is you loose the ability to identify and report what fields are incorrectly set to null. I'm going to stick with explicit field level annotations for now.
Paco