如何使用 javax.validation 将 @NotNull 约束应用于类中的所有字段?
我正在使用 javax.validation 的 hibernate 实现,并且想知道是否有人能够将 @NotNull 约束注释应用于类的所有字段,而不是每个单独的字段?
我更愿意在我的项目中强制执行 @NotNull 约束作为默认值,以避免每个字段上都带有 @NotNull 注释的代码。理想情况下,最好定义一个自定义约束“@MayBeNull”来注释任何可能为空的字段。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的情况下,验证所有字段是否为 null 真的有意义吗?例如,对于 int、long 等基本类型怎么样?
无论如何,Bean Validation 不提供您所要求的功能。您可以编写一个自定义类约束@MyNotNull,它通过反射验证所有字段是否为空。我个人建议反对。
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.