且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

注释@Id 和@GeneratedValue(strategy = GenerationType.IDENTITY) 的用途是什么?为什么生成类型是身份?

更新时间:2021-09-16 09:08:14

首先,使用注解作为我们的配置方法只是一种方便的方法,而不是应付无穷无尽的 XML 配置文件.

First of all, using annotations as our configure method is just a convenient method instead of coping the endless XML configuration file.

@Id注解继承自javax.persistence.Id,表示下面的成员字段是当前实体的主键.因此,您的 Hibernate 和 spring 框架以及您可以基于此注释执行一些 reflect 工作.详情请查看javadoc for Id

The @Idannotation is inherited from javax.persistence.Id, indicating the member field below is the primary key of current entity. Hence your Hibernate and spring framework as well as you can do some reflect works based on this annotation. for details please check javadoc for Id

@GeneratedValue注解用于配置指定列(字段)的递增方式.例如在使用Mysql时,可以在表的定义中指定auto_increment使其自增,然后使用

The @GeneratedValue annotation is to configure the way of increment of the specified column(field). For example when using Mysql, you may specify auto_increment in the definition of table to make it self-incremental, and then use

@GeneratedValue(strategy = GenerationType.IDENTITY)

在 Java 代码中表示您也承认使用此数据库服务器端策略.此外,您可以更改此注释中的值以适应不同的需求.

in the Java code to denote that you also acknowledged to use this database server side strategy. Also, you may change the value in this annotation to fit different requirements.

例如,Oracle 必须使用 sequence 作为增量方法,假设我们在 Oracle 中创建了一个序列:

For instance, Oracle has to use sequence as increment method, say we create a sequence in Oracle:

create sequence oracle_seq;

2.参考数据库序列

既然我们在数据库中有了序列,但是我们需要建立Java和DB之间的关系,通过使用@SequenceGenerator:

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

sequenceName 在 Oracle 中是一个序列的真实名称,name 是你想在 Java 中调用它的名字.如果sequenceNamename 不同,则需要指定sequenceName,否则就使用name.我通常会忽略 sequenceName 以节省时间.

sequenceName is the real name of a sequence in Oracle, name is what you want to call it in Java. You need to specify sequenceName if it is different from name, otherwise just use name. I usually ignore sequenceName to save my time.

最后,是时候在 Java 中使用这个序列了.只需添加 @GeneratedValue:

Finally, it is time to make use this sequence in Java. Just add @GeneratedValue:

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

generator 字段指的是您要使用的序列生成器.注意它不是数据库中真正的序列名称,而是您在SequenceGeneratorname字段中指定的名称.

The generator field refers to which sequence generator you want to use. Notice it is not the real sequence name in DB, but the name you specified in name field of SequenceGenerator.

所以完整版应该是这样的:

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;
}

现在开始使用这些注解让您的 JavaWeb 开发更容易.

Now start using these annotations to make your JavaWeb development easier.