JPA要求每一个实体必须有且只有一个主键,而@GeneratedValue提供了主键的生成策略,这就是@GeneratedValue注解存在的意义。本文将浅析@GeneratedValue的源码。

@GeneratedValue的源码如下:

/*
* Copyright (c) 2008, 2009, 2011 Oracle, Inc. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution. The Eclipse Public License is available
* at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License
* is available at http://www.eclipse.org/org/documents/edl-v10.php.
*/
package javax.persistence; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static javax.persistence.GenerationType.AUTO; /**
* Provides for the specification of generation strategies for the
* values of primary keys.
*
* <p> The <code>GeneratedValue</code> annotation
* may be applied to a primary key property or field of an entity or
* mapped superclass in conjunction with the {@link Id} annotation.
* The use of the <code>GeneratedValue</code> annotation is only
* required to be supported for simple primary keys. Use of the
* <code>GeneratedValue</code> annotation is not supported for derived
* primary keys.
*
* <pre>
*
* Example 1:
*
* @Id
* @GeneratedValue(strategy=SEQUENCE, generator="CUST_SEQ")
* @Column(name="CUST_ID")
* public Long getId() { return id; }
*
* Example 2:
*
* @Id
* @GeneratedValue(strategy=TABLE, generator="CUST_GEN")
* @Column(name="CUST_ID")
* Long id;
* </pre>
*
* @see Id
* @see TableGenerator
* @see SequenceGenerator
*
* @since Java Persistence 1.0
*/
@Target({METHOD, FIELD})
@Retention(RUNTIME) public @interface GeneratedValue { /**
* (Optional) The primary key generation strategy
* that the persistence provider must use to
* generate the annotated entity primary key.
*/
GenerationType strategy() default AUTO; /**
* (Optional) The name of the primary key generator
* to use as specified in the {@link SequenceGenerator}
* or {@link TableGenerator} annotation.
* <p> Defaults to the id generator supplied by persistence provider.
*/
String generator() default "";
}

@Target({METHOD, FIELD})说明该注解可以用于方法声明和域声明。

@Retention(RUNTIME)说明该注解在VM运行期间也可以保留,可以通过反射机制读取注解的信息。

如果不是很清楚,可参考@Controller和@Restcontroller源码解析中有对元注解的介绍。

@GeneratedValue注解有两个属性,分别是strategy和generator,其中generator属性的值是一个字符串,默认为"",其声明了主键生成器的名称。

查看GenerationType的源码,可以看到定义了四种主键生成策略:TABLE,SEQUENCE,IDENTITY,AUTO。

/*
* Copyright (c) 2008, 2009, 2011 Oracle, Inc. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution. The Eclipse Public License is available
* at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License
* is available at http://www.eclipse.org/org/documents/edl-v10.php.
*/
package javax.persistence; /**
* Defines the types of primary key generation strategies.
*
* @see GeneratedValue
*
* @since Java Persistence 1.0
*/
public enum GenerationType { /**
* Indicates that the persistence provider must assign
* primary keys for the entity using an underlying
* database table to ensure uniqueness.
*/
TABLE, /**
* Indicates that the persistence provider must assign
* primary keys for the entity using a database sequence.
*/
SEQUENCE, /**
* Indicates that the persistence provider must assign
* primary keys for the entity using a database identity column.
*/
IDENTITY, /**
* Indicates that the persistence provider should pick an
* appropriate strategy for the particular database. The
* <code>AUTO</code> generation strategy may expect a database
* resource to exist, or it may attempt to create one. A vendor
* may provide documentation on how to create such resources
* in the event that it does not support schema generation
* or cannot create the schema resource at runtime.
*/
AUTO
}

TABLE

使用数据库表来生成主键。该策略一般与另外一个注解一起使用@TableGenerator,@TableGenerator注解指定了生成主键的表(可以在实体类上指定也可以在主键字段或属性上指定),然后JPA将会根据注解内容自动生成一张表作为序列表(或使用现有的序列表)。如果不指定序列表,则会生成一张默认的序列表,表中的列名也是自动生成,数据库上会生成一张名为sequence的表(SEQ_NAME,SEQ_COUNT)。序列表一般只包含两个字段:第一个字段是该生成策略的名称,第二个字段是该关系表的最大序号,它会随着数据的插入逐渐累加。该策略的好处就是不依赖于外部环境和数据库的具体实现,便于移植;但由于其不能充分利用数据库的特性,所以不会优先使用。

    @Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "roleSeq")
@TableGenerator(name = "roleSeq", allocationSize = 1, table = "seq_table", pkColumnName = "seq_id", valueColumnName = "seq_count")
private Long id;

SEQUENCE

使用序列来生成主键。 该策略的不足之处正好与TABLE相反,由于只有部分数据库(Oracle,PostgreSQL,DB2)支持序列对象,所以该策略一般不应用于其他数据库。需要注意,MySQL不支持这种主键生成策略。该策略一般与另外一个注解一起使用@SequenceGenerator,@SequenceGenerator注解指定了生成主键的序列.然后JPA会根据注解内容创建一个序列(或使用一个现有的序列)。如果不指定序列,则会自动生成一个序列SEQ_GEN_SEQUENCE。

    @Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "menuSeq")
@SequenceGenerator(name = "menuSeq", initialValue = 1, allocationSize = 1, sequenceName = "MENU_SEQUENCE")
private Long id;

IDENTITY

使用数据库ID自增长的方式来生成主键。 该策略在大部分数据库中都提供了支持(指定方法或关键字可能不同),但还是有少数数据库(Oracle)不支持,所以可移植性略差。

    @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

AUTO

自动选择合适的主键生成策略。该策略比较常用,也是默认选项,@GeneratedValue(strategy = GenerationType.AUTO)相当于@GeneratedValue。

    @Id
@GeneratedValue
private Long id;

参考:JPA之@GeneratedValue注解。这篇介绍的挺详细的,推荐一下。

最新文章

  1. [已解决] git 重命名文件夹
  2. C#控件根据窗体改变大小
  3. Unix时间戳(Unix timestamp)转换工具
  4. 内存对齐-C语言struct内存占用问题
  5. Hibernate各种主键生成策略2
  6. 集成支付宝报一堆warning: (arm64) /Users/scmbuild/workspace/standard-pay/.....警告问题解决办法亲测可行!
  7. 【Java学习笔记之十二】Java8增强的工具类:Arrays的用法整理总结
  8. ajax中xmlhttp.readyState和xmlhttp.status的值及解释
  9. juypter4.4.0 自动补全
  10. 虚拟机上安装django链接Pycharm(版本差异有所差异)
  11. 【JVM】-NO.114.JVM.1 -【JDK11 HashMap详解-3-put-treeifyBin()-AVL】
  12. Windows cmd 一些命令
  13. capjoint一些生成文件的解释
  14. JDBC之 自增长与事务
  15. LInux内核分析--使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用
  16. day7 socket网络编程基础
  17. 3D有向包围盒与球体碰撞的算法
  18. Hibernate--关系映射和关联关系的CRUD
  19. MySQL-&gt;AUTO_INCREMENT[20180516]
  20. 论文阅读 | FPN:Feature Pyramid Networks for Object Detection

热门文章

  1. xml、网络编程、 反射
  2. python_黑洞数
  3. 计算机网络相关:应用层协议(二):HTTP
  4. java位 、字节 、字符的梳理
  5. 【Java入门提高篇】Java集合类详解(一)
  6. 《嵌入式Linux内存使用与性能优化》笔记
  7. Linux时间子系统之(十七):ARM generic timer驱动代码分析
  8. eclipse如何新建项目发布到git
  9. 找jar包的网站 还没用过2017.12.19
  10. CentOS 7.2 关闭防火墙