> For the complete documentation index, see [llms.txt](https://spring-boot.shujuwajue.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://spring-boot.shujuwajue.com/guan-xi-xing-shu-ju-ku/spring-data-jpa/id-he-generatedvalue-xiang-jie.md).

# @Id 和 @GeneratedValue 详解

## @Id：

@Id 标注用于声明一个实体类的属性映射为数据库的主键列。（也就是标注字段是primary key）

## @GeneratedValue：

@GeneratedValue 用于标注主键的生成策略，通**过strategy 属性**指定。

默认情况下，JPA 自动选择一个最适合底层数据库的主键生成策略：SqlServer对应identity，MySQL 对应 auto increment。

在javax.persistence.GenerationType中定义了以下几种可供选择的策略：

```java
public enum GenerationType{    
    TABLE,    
    SEQUENCE,    
    IDENTITY,    
    AUTO   
}
```

* IDENTITY：采用数据库ID自增长的方式来自增主键字段，Oracle 不支持这种方式；
* AUTO： JPA自动选择合适的策略，是默认选项；
* SEQUENCE：通过序列产生主键，通过@SequenceGenerator 注解指定序列名，MySql不支持这种方式
* TABLE：通过表产生主键，框架借由表模拟序列产生主键，使用该策略可以使应用更易于数据库移植。

也就是如果你没有指定**strategy属性，默认策略是**AUTO，JPA会根据你使用的数据库来自动选择策略，比如说我使用的是mysql则，自动的主键策略就是IDENTITY （auto increment）。

## 资料

[4. JPA @Id 和 @GeneratedValue 注解详解](https://blog.csdn.net/rickesy/article/details/50788161)

[理解JPA注解@GeneratedValue](https://blog.csdn.net/canot/article/details/51455967)

[JPA ID生成策略](http://tendyming.iteye.com/blog/2024985)
