我正在阅读本教程 ,是否有任何定义主键的注释值是多余的?
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false, updatable = false) private Long id;换句话说,作者可能只有:
@Id private Long id;得到相同的结果?
I'm reading through this tutorial and was whether any of the annotation values defining the primary key are redundant?
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false, updatable = false) private Long id;In other words could the author just have:
@Id private Long id;And get the same result?
最满意答案
没有任何注释是多余的 。 它们中的每一个都会影响非常具体的行为,具体取决于您的域模型的需求。
@ID 此批注标识应该参与实体主键的属性/字段。 @GeneratedValue 此批注允许指定应如何派生属性/字段的值。 如果省略此注释,则假定该值由应用程序提供。 @柱 此注释描述属性/字段的模式表示,指定名称,插入的特征,可更新性和可空性设置等。通过省略此批注,persister提供程序将使用一系列默认值来表示数据库模式表示财产/领域。在前面的例子中,标识符值将由数据库级别的AUTO_INCREMENT或IDENTITY表示派生,并将映射到名为“id”的字段,该字段不为空。
在后一示例中,假设提供标识符值,因此必须在持久化实体之前设置它。 排除@Column注释与此特定情况无关,因为Hibernate将使用以属性名称命名的列,因此将使用字段“id”。 主键默认情况下不可为空且不可更新。
None of the annotations are redundant. Each of them influence very specific behavior, depending upon the needs of your domain model.
@Id This annotation identifies a property/field that should participate in the entity's primary key. @GeneratedValue This annotation allows specifying how the value of the property/field should be derived. Should this annotation be omitted, the value is assumed to be provided by the application. @Column This annotation describes the schema representation of the property/field, specifying the name, characteristics about its insertion, updatability, and nullability settings, etc. By omitting this annotation, the persister provider will use a series of default values to represent the database schema representation of the property/field.Ergo, in your former example, the identifier value will be derived by an AUTO_INCREMENT or IDENTITY representation at the database level and will be mapped to a field named "id" which is not null.
In the latter example, the identifier value is assumed to be provided, thus it must be set before persisting the entity. The exclusion of the @Column annotation is irrelevant in this specific case because Hibernate will use a column named after the property name, thus a field "id" will be used. Primary keys are by default not nullable and not updatable.
更多推荐
发布评论