简体   繁体   English

注释@Id 和@GeneratedValue(strategy = GenerationType.IDENTITY) 有什么用? 为什么世代类型是身份?

[英]what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY)

Why we are using this annotations?为什么我们使用这个注解? i need to know if this autoincrement my table id values.我需要知道这是否会自动增加我的表 id 值。 (GenerationType.IDENTITY) is there any other types whats actually happening when we use this annotation (GenerationType.IDENTITY) 是否有任何其他类型在我们使用此注释时实际发生了什么

public class Author extends Domain
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id") 
    private Integer id;

    @Basic(optional = false)
    @Column(name = "name") 
    private String name;

    @Column(name = "address") 
    private String address; 

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "authorId")
    private List<Book>
    bookList;

    public Author()
    { 
        setServiceClassName("wawo.tutorial.service.admin.AuthorService");
    }
}

*Is it necessary to extend Domain abstract class?What is the use? *是否需要扩展Domain abstract class?有什么用?

First of all, using annotations as our configure method is just a convenient method instead of coping the endless XML configuration file.首先,使用注解作为我们的配置方法只是一种方便的方法,而不是应付无穷无尽的 XML 配置文件。

The @Id annotation is inherited from javax.persistence.Id , indicating the member field below is the primary key of current entity. @Id注解继承自javax.persistence.Id ,表示下面的成员字段是当前实体的主键。 Hence your Hibernate and spring framework as well as you can do some reflect works based on this annotation.因此,您的 Hibernate 和 spring 框架以及您可以根据此注释进行一些reflect工作。 for details please check javadoc for Id有关详细信息,请查看javadoc 以获取 ID

The @GeneratedValue annotation is to configure the way of increment of the specified column(field). @GeneratedValue注解是配置指定列(字段)的递增方式。 For example when using Mysql , you may specify auto_increment in the definition of table to make it self-incremental, and then use比如在使用Mysql ,可以在表的定义中指定auto_increment使其自增,然后使用

@GeneratedValue(strategy = GenerationType.IDENTITY)

in the Java code to denote that you also acknowledged to use this database server side strategy.在 Java 代码中表示您也承认使用此数据库服务器端策略。 Also, you may change the value in this annotation to fit different requirements.此外,您可以更改此注释中的值以适应不同的要求。

1. Define Sequence in database 1.在数据库中定义序列

For instance, Oracle has to use sequence as increment method, say we create a sequence in Oracle:例如,Oracle 必须使用sequence作为增量方法,假设我们在 Oracle 中创建一个序列:

create sequence oracle_seq;

2. Refer the database sequence 2.参考数据库序列

Now that we have the sequence in database, but we need to establish the relation between Java and DB, by using @SequenceGenerator :现在我们在数据库中有了序列,但是我们需要通过使用@SequenceGenerator来建立 Java 和 DB 之间的关系:

@SequenceGenerator(name="seq",sequenceName="oracle_seq")

sequenceName is the real name of a sequence in Oracle, name is what you want to call it in Java. sequenceName在 Oracle 中是一个序列的真实名称,在 Java 中, name就是你想叫它的name You need to specify sequenceName if it is different from name , otherwise just use name .如果与name不同,则需要指定sequenceName ,否则只需使用name I usually ignore sequenceName to save my time.我通常会忽略sequenceName以节省时间。

3. Use sequence in Java 3.在Java中使用序列

Finally, it is time to make use this sequence in Java.最后,是时候在 Java 中使用这个序列了。 Just add @GeneratedValue :只需添加@GeneratedValue

@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")

The generator field refers to which sequence generator you want to use. generator字段是指您要使用的序列生成器。 Notice it is not the real sequence name in DB, but the name you specified in name field of SequenceGenerator .请注意,它不是 DB 中的真实序列名称,而是您在SequenceGenerator name字段中指定的name

4. Complete 4. 完成

So the complete version should be like this:所以完整版应该是这样的:

public class MyTable
{
    @Id
    @SequenceGenerator(name="seq",sequenceName="oracle_seq")        
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")               
    private Integer pid;
}

Now start using these annotations to make your JavaWeb development easier.现在开始使用这些注释来使您的 JavaWeb 开发更容易。

In a Object Relational Mapping context, every object needs to have a unique identifier.在对象关系映射上下文中,每个对象都需要有一个唯一的标识符。 You use the @Id annotation to specify the primary key of an entity.您可以使用@Id注释来指定实体的主键。

The @GeneratedValue annotation is used to specify how the primary key should be generated. @GeneratedValue注释用于指定应如何生成主键。 In your example you are using an Identity strategy which在您的示例中,您使用的是Identity策略

Indicates that the persistence provider must assign primary keys for the entity using a database identity column.指示持久性提供程序必须使用数据库标识列为实体分配主键。

There are other strategies, you can see more here .还有其他策略,你可以在这里看到更多。

Simply, @Id: This annotation specifies the primary key of the entity. 

@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used. 

GenerationType enum defines four strategies: 
1. Generation Type . TABLE, 
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY   
4. Generation Type. AUTO

GenerationType.SEQUENCE

With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities. 

GenerationType.TABLE

With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities. 

GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.

GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used. 

Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html参考:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html

Why are we using this annotation?我们为什么要使用这个注解?

  • First I would like to remind everyone that the annotations, such as @Id , are providing metadata to the persistence layer(I will assume hibernate).This metadata will most likely be stored in the.class file(but not stored in the database) and is used to tell hibernate how to recognize, interpret and manage the entity.首先我想提醒大家,注解,例如@Id ,正在为持久层提供元数据(我假设休眠)。这个元数据很可能存储在.class文件中(但不存储在数据库中)并用于告诉 hibernate 如何识别、解释和管理实体。 So, Why are you using the annotation?那么,你为什么要使用注解呢? To provide your persistence layer with the proper information about how to manage the entity.为您的持久层提供有关如何管理实体的正确信息。

Why use the @Id annotation?为什么要使用@Id 注解?

  • The @Id annotation is one of the two mandatory annotations needed when creating an entity with JPA. @Id注解是使用 JPA 创建实体时所需的两个必需注解之一。 The other one being @Entity .另一个是@Entity @Id does two things for us: @Id为我们做了两件事:

    1) signifies that this field will be the unique identifier for this class when mapped to a database table 1)表示此字段在映射到数据库表时将是此 class 的唯一标识符

    2) the presence of @Id lets the persistence layer know that all other fields within this class are to be mapped to database rows 2) @Id的存在让持久层知道此 class 中的所有其他字段都将映射到数据库行

Why use @GeneratedValue?为什么使用@GeneratedValue?

  • By marking the @Id field with @GeneratedValue we are now enabling id generation .通过用@GeneratedValue标记@Id字段,我们现在启用id generation Which means that the persistence layer will generate an Id value for us and handle the auto incrementing.这意味着持久层将为我们生成一个 Id 值并处理自动递增。 Our application can choose 1 of 4 generations strategies:我们的应用程序可以选择 4 代策略中的 1 个:

    1) AUTO 1) 自动

    2) TABLE 2) 表

    3) SEQUENCE 3) 序列

    4) IDENTITY 4) 身份

  • If not strategy is specified then AUTO is assumed如果未指定策略,则假定为 AUTO

What is strategy = GenerationType.IDENTITY actually doing? strategy = GenerationType.IDENTITY 实际上在做什么?

  • When we specify the generation strategy as GenerationType.IDENTITY we are telling the persistence provider(hibernate) to let the database handle the auto incrementing of the id.当我们将生成策略指定为GenerationType.IDENTITY时,我们告诉持久性提供程序(休眠)让数据库处理 id 的自动递增。 If you were to use postgres as an underling database and specified the strategy as IDENTITY , hibernate would execute this:如果您使用 postgres 作为基础数据库并将策略指定为IDENTITY , hibernate 将执行以下操作:
create table users (
       id  bigserial not null,
        primary key (id)
    )

  • Notice that they type of the id is bigserial , what is bigserial?请注意,他们的 id 类型是bigserial ,什么是 bigserial? As per the postgres documentation , bigserial is a large autoincrementing integer .根据 postgres文档bigserial is a large autoincrementing integer

Conclusion结论

  • By specifying:通过指定:
@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

  • you have told the underlying persistence layer to use the id field as a unique identifier within the database.您已经告诉底层持久层使用 id 字段作为数据库中的唯一标识符。 Also told the persistence layer to let the database handle the auto incrementing of the id with GenerationType.IDENTITY .还告诉持久层让数据库使用GenerationType.IDENTITY处理 id 的自动递增。

In very simple words, We want to tell our DataBase(DB) to what strategy to use to generate Primary Keys.简单来说,我们想告诉我们的数据库(DB)使用什么策略来生成主键。 Now, Primary Keys must be different for every different row so there must be some stratergy that will tell DB on how to differentiate one row from another.现在,每个不同行的主键都必须不同,因此必须有一些策略来告诉数据库如何区分一行与另一行。

GenerationType let us define that strategy GenerationType 让我们定义该策略

Here @GeneratedValue(stratergy=GenerationType.IDENTITY) is telling our DB to store Primary Key in Identity Column which is a default column in SQL for Default Auto Incremented Primary Key Generation.这里@GeneratedValue(stratergy=GenerationType.IDENTITY) 告诉我们的数据库将主键存储在身份列中,这是 SQL 中默认自动递增主键生成的默认列。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring Boot @GeneratedValue(strategy = GenerationType.IDENTITY) 不起作用 - Spring Boot @GeneratedValue(strategy = GenerationType.IDENTITY) not working 问题 java @GeneratedValue (strategy = GenerationType.IDENTITY) 使用 MariaDB 10.4 和 eclipselink - Problems with java @GeneratedValue (strategy = GenerationType.IDENTITY) using MariaDB 10.4 and eclipselink 在填充的数据库中使用@GeneratedValue(strategy = GenerationType.IDENTITY)会导致PK约束错误 - Using @GeneratedValue(strategy=GenerationType.IDENTITY) in populated database causes PK constraint error 全局配置Hibernate以使用GenerationType.IDENTITY - Configure Hibernate globally to use GenerationType.IDENTITY 为什么在使用策略GenerationType.IDENTITY时Hibernate尝试访问hibernate_sequence? - Why is Hibernate trying to access hibernate_sequence when using strategy GenerationType.IDENTITY? 休眠中的 GenerationType.AUTO 与 GenerationType.IDENTITY - GenerationType.AUTO vs GenerationType.IDENTITY in hibernate Hibernate GenerationType.IDENTITY vs GenerationType.SEQUENCE - Hibernate GenerationType.IDENTITY vs GenerationType.SEQUENCE @ GenerationType.IDENTITY失败10以上 - @GenerationType.IDENTITY failing above 10 休眠:@GeneratedValue(strategy = GenerationType - Hibernate: @GeneratedValue(strategy = GenerationType 在为GenerationType.IDENTITY提供标识符值作为生成标识符的策略时,传递给分离的实体 - Detached entity passed to persist when providing identifier value for GenerationType.IDENTITY as strategy to generate the identifier
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM