我为什么要指定@Column(nullable = false)? [英] Why should I specify @Column( nullable = false )?

查看:3445
本文介绍了我为什么要指定@Column(nullable = false)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 @Entity 注释的实体。

如果我负责创建 CREATE TABLE 脚本为什么我可以指定 @Column(nullable = false)当我可以在数据库中使用 NOT NULL 关键字?是否有任何示例显示在字段中使用此属性的好处?

I have an entity annotated with @Entity.
If I am responsible for creating the CREATE TABLE scripts why should I specify @Column( nullable = false ) when I can create a column in the database with the NOT NULL keywords? Is there any example that shows the benefits of using this property in a field?

推荐答案

更好的错误消息和错误处理,尤其是您还可以添加 JSR303 @NotNull注释

Better error messages and error handling, especially if you also add the JSR303 @NotNull annotation.

如果你创建列为 NOT NULL 但是不告诉JPA它不是null,JPA将假设空值是可以的。当您尝试使用空值保存对象时,它将继续将其发送到数据库,您将收到数据库级错误。这会增加数据库中的日志垃圾邮件,并且很难从错误中确定哪个表是哪个表的问题,更不用说将它们映射回他们的JPA名称。

If you create the column as NOT NULL but don't tell JPA it's not null, JPA will assume that null values are OK. When you try to save an object with nulls, it'll proceed to send that to the DB and you'll get a DB level error. This increases log spam in the database and it's much harder to determine from the error which column(s) of which table(s) were the problem, let alone map them back to their JPA names.

如果您将它们注释为非null,JPA将在保存之前抛出异常,避免数据库日志垃圾邮件,并且通常会给您带来更好的错误。特别是,如果您的JPA提供程序支持JSR303并在内部将 nullable = false 转换为 @NotNull ,或者您已添加 @NotNull ,它还会为您提供一个数据结构,您可以检查该数据结构以确切了解哪些对象因哪些原因而被拒绝,以及可自定义的模板化错误消息。

If you annotate them as not null, JPA will throw an exception before saving, avoiding DB log spam and usually giving you a better error. In particular, if your JPA provider supports JSR303 and either translates nullable=false into @NotNull internally or you've added @NotNull too, it'll give you a data structure you can examine to see exactly what fields of what objects were rejected for what reasons, along with customisable templated error messages.

这就是为什么你应该告诉JPA NOT NULL 字段。这样,在不需要阅读数据库架构的情况下,处理代码的其他人也更容易理解。

That's why you should tell JPA about NOT NULL fields. That, and it's easier for others working on your code to understand without also having to read the DB schema.

这篇关于我为什么要指定@Column(nullable = false)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆