> 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)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://spring-boot.shujuwajue.com/guan-xi-xing-shu-ju-ku/spring-data-jpa/id-he-generatedvalue-xiang-jie.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
