如何为 @Column(nullable = false) 添加自定义消息?

huangapple go评论101阅读模式
英文:

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 是完全独立的事物。

  1. 只有在使用 Hibernate 模式生成 时,@Column(nullable = false) 才有意义。违反此约束将导致数据库级错误,并附带特定于数据库的错误消息。

  2. @NotNullbean 验证 的一部分。违反此约束将导致应用程序级错误,可以进行自定义设置。

英文:

Actually, the @Column(nullable = false) and @NotNull are completely independent things.

  1. 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.

  2. The @NotNull is a part of bean validation. And violation of this constraint will lead to the application level error that can be customized.

huangapple
  • 本文由 发表于 2020年9月22日 14:38:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/64004302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定