英文:
How can I add a custom message for @Column(nullable = false)?
问题
我之前是这样使用 @NotNull 来验证类的字段的:@NotNull(message = "Vendor ID must be fetched from Orders")
。然而,我决定用数据库级别的约束替换 @NotNull
验证,使用 @Column(nullable = false)
。有没有办法为这个验证添加自定义消息,类似于 @NotNull
版本的验证中的消息,以便在违反约束的情况下得到指定的消息?
英文:
I was previously using @NotNull to validate the fields of a class as follows: @NotNull(message = "Vendor ID must be fetched from Orders")
. However, I decided to replace the @NotNull
validation with database-level constraints, using @Column(nullable = false)
. Is there any way to add the custom message to this validation, similar to the one present with the @NotNull
version of the validation, such that I get the specified message in case of violation of the constraint?
答案1
得分: 1
因为@Column
描述的是数据库属性,所以它无法在您希望的级别上进行验证:如果您使用@Column(nullable = false)
,您并没有表示setter参数不能为null,而是表示该列不能为null,因此您将在数据库级别上进行验证并获得一条消息。
英文:
Since @Column
describes a db property, it cannot do a validation at the level you want: if you say @Column(nullable = false)
, you are not saying the setter parameter cannot be null, you are saying that that column cannot be null, so you will have a validation and a message at the database level.
答案2
得分: 1
实际上,@Column(nullable = false)
和 @NotNull
是完全独立的事物。
-
只有在使用 Hibernate 模式生成 时,
@Column(nullable = false)
才有意义。违反此约束将导致数据库级错误,并附带特定于数据库的错误消息。 -
@NotNull
是 bean 验证 的一部分。违反此约束将导致应用程序级错误,可以进行自定义设置。
英文:
Actually, the @Column(nullable = false)
and @NotNull
are completely independent things.
-
The
@Column(nullable = false)
make sense only if you use hibernate schema generation. And violation of this constraint will lead to the db level error with db specific error message. -
The
@NotNull
is a part of bean validation. And violation of this constraint will lead to the application level error that can be customized.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论