这些jpa注释值中的任何一个都是多余的吗?(Are any of these jpa annotation values redundant?)

编程入门 行业动态 更新时间:2024-10-27 22:25:18
这些jpa注释值中的任何一个都是多余的吗?(Are any of these jpa annotation values redundant?)

我正在阅读本教程 ,是否有任何定义主键的注释值是多余的?

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

更多推荐

本文发布于:2023-07-22 12:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219893.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:都是   任何一个   注释   多余   jpa

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!