问题描述
当它们出现在
@Entity
的字段/getter 上时,它们之间有什么区别?(我通过 Hibernate 持久化实体).
When they appear on a field/getter of an
@Entity
, what is the difference between them? (I persist the Entity through Hibernate).
它们各自属于哪个框架和/或规范?
What framework and/or specification each one of them belongs to?
@NotNull
位于 javax.validation.constraints
内.在 javax.validation.constraints.NotNull
javadoc 它说
@NotNull
is located within javax.validation.constraints
. In the javax.validation.constraints.NotNull
javadoc it says
被注解的元素不能为空
但是它没有提到元素在数据库中的表示,那我为什么要在列中添加约束nullable=false
?
but it does not speak of the element's representation in the database, so why would I add the constraint nullable=false
to the column?
推荐答案
@NotNull
是一个 JSR303 Bean 验证注解.它与数据库约束本身无关.但是,由于 Hibernate 是 JSR 303 的参考实现,它可以智能地获取这些约束并将它们转换为数据库约束,因此您可以花一个的价格获得两个.@Column(nullable = false)
是将列声明为非空的 JPA 方式.IE.前者用于验证,后者用于指示数据库模式详细信息.您只是从 Hibernate 获得了一些关于验证注释的额外(欢迎!)帮助.
@NotNull
is a JSR 303 Bean Validation annotation. It has nothing to do with database constraints itself. As Hibernate is the reference implementation of JSR 303, however, it intelligently picks up on these constraints and translates them into database constraints for you, so you get two for the price of one. @Column(nullable = false)
is the JPA way of declaring a column to be not-null. I.e. the former is intended for validation and the latter for indicating database schema details. You're just getting some extra (and welcome!) help from Hibernate on the validation annotations.
这篇关于混淆:@NotNull 与 @Column(nullable = false) 与 JPA 和 Hibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!