Category: Spring Updated: Aug 08, 2026

Complete Guide to Spring @GeneratedValue for Java Beginners – Understand Primary Key Generation in JPA

Spring @GeneratedValue Annotation Tutorial for Beginners
Spring @GeneratedValue Annotation Tutorial for Beginners

Understand with a Teacher and Student Conversation

Student

"How are IDs automatically created in a Spring Boot application when saving data?"

Teacher

"In Spring and JPA, you can use the @GeneratedValue annotation to automatically generate primary keys."

Student

"So I do not need to manually set the ID?"

Teacher

"Exactly. The database or JPA provider will handle ID generation for you."

Student

"Are there different ways to generate IDs?"

Teacher

"Yes. There are several strategies, and each one works differently. Let’s explore them step by step."

1. What is GeneratedValue in JPA

1. What is GeneratedValue in JPA
1. What is GeneratedValue in JPA

The @GeneratedValue annotation in Java is used in JPA to automatically generate values for primary keys. It is commonly used in Spring Boot applications when working with databases.

In Java programming basics and modern web development, managing primary keys manually can lead to errors. Using automatic ID generation helps developers avoid duplication and simplifies database operations.

For Java beginners learning Spring Boot and JPA, understanding how primary keys work is an essential step.

2. Basic Usage of GeneratedValue

2. Basic Usage of GeneratedValue
2. Basic Usage of GeneratedValue

To use @GeneratedValue, you first need to define a primary key using the @Id annotation.


import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;

@Entity
public class User {

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

    private String name;
}

In this example, the ID will be automatically generated when a new User is saved.


ID generated automatically

3. GenerationType Strategies Explained

3. GenerationType Strategies Explained
3. GenerationType Strategies Explained

There are several strategies available for generating IDs in JPA.

  • AUTO: JPA decides the best strategy
  • IDENTITY: Uses database auto increment
  • SEQUENCE: Uses database sequence
  • TABLE: Uses a table to manage IDs

Choosing the correct strategy depends on your database and performance requirements.

4. Using Identity Strategy

4. Using Identity Strategy
4. Using Identity Strategy

The IDENTITY strategy is the most common for beginners. It relies on the database auto increment feature.


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

This works well with databases like MySQL and PostgreSQL.

5. Using Sequence Strategy

5. Using Sequence Strategy
5. Using Sequence Strategy

The SEQUENCE strategy uses a database sequence to generate IDs. It is often used in enterprise systems.


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

This approach can improve performance when handling large amounts of data.

6. Using Auto Strategy

6. Using Auto Strategy
6. Using Auto Strategy

The AUTO strategy lets JPA choose the best generation method.


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

This is useful for beginners who do not want to worry about database-specific details.

7. How GeneratedValue Works Internally

7. How GeneratedValue Works Internally
7. How GeneratedValue Works Internally

When an entity is saved, the persistence provider communicates with the database to generate a unique ID. This process ensures that each record has a unique identifier.

Understanding this flow helps Java beginners learn how Spring Boot interacts with databases.

8. Common Mistakes and Tips

8. Common Mistakes and Tips
8. Common Mistakes and Tips

Beginners often make mistakes such as forgetting the @Id annotation or choosing the wrong strategy.

  • Always define a primary key
  • Use IDENTITY for simple projects
  • Use SEQUENCE for better performance
  • Test with your database

Avoiding these mistakes will help you build stable applications.

9. Practical Example with Repository

9. Practical Example with Repository
9. Practical Example with Repository

Let’s see how @GeneratedValue works with a repository in Spring Boot.


import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

When you save a new entity, the ID will be generated automatically.


User user = new User();
user.setName("John");
userRepository.save(user);

User saved with generated ID

This demonstrates how Spring Data JPA simplifies database operations.

Summary

Summary
Summary

The GeneratedValue annotation in Spring Boot and JPA is one of the most essential features for managing primary keys in modern Java applications. It allows developers to automatically generate unique identifiers without manually handling ID values, which significantly reduces the risk of duplication and human error. For Java beginners, this feature simplifies database interaction and improves code readability and maintainability.

In this guide, we explored how GeneratedValue works together with the Id annotation to define primary keys in entity classes. By using different generation strategies such as IDENTITY, SEQUENCE, AUTO, and TABLE, developers can adapt their applications to various database environments and performance requirements. Understanding these strategies is an important part of Java programming basics and helps build a strong foundation for working with Spring Boot and JPA.

One of the most commonly used strategies for beginners is the IDENTITY strategy, which relies on database auto increment features. This approach is simple and works well with many relational databases such as MySQL and PostgreSQL. On the other hand, the SEQUENCE strategy is often used in enterprise applications where performance optimization is required. Choosing the correct strategy depends on the specific needs of your application and the capabilities of your database system.

Another important concept is how the persistence provider manages ID generation internally. When an entity is saved, the system communicates with the database to generate a unique value. This process is handled automatically, allowing developers to focus on business logic instead of low level database operations. For beginners learning Java tutorial for beginners and Spring Boot development, this abstraction is extremely helpful.

In addition, applying GeneratedValue correctly helps ensure that your application remains scalable and consistent. As your application grows, proper ID management becomes increasingly important. Developers should always test their configuration with their chosen database and confirm that IDs are generated correctly under different scenarios.

It is also important to avoid common mistakes such as forgetting to define the Id annotation or using an incompatible generation strategy. These issues can lead to runtime errors or unexpected behavior. By understanding how GeneratedValue works and practicing with simple examples, developers can quickly gain confidence in using JPA effectively.

Sample Program Using Identity Strategy


import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;

@Entity
public class Product {

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

    private String name;
}

ID generated automatically when saving Product

Sample Program Using Sequence Strategy


import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;

@Entity
public class Order {

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

    private String item;
}

Sequence based ID generated

Sample Program Saving Data


Order order = new Order();
order.setItem("Book");
orderRepository.save(order);

Order saved with generated ID

Sample Program Using Auto Strategy


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

JPA selected appropriate strategy automatically
Review Conversation Between the Teacher and Student

Student

"I understand that GeneratedValue creates IDs automatically but why is it important in real applications"

Teacher

"It is important because it guarantees that each record has a unique identifier without manual work which reduces errors"

Student

"Should I always use the identity strategy as a beginner"

Teacher

"Identity is a good starting point but you should also understand other strategies for different situations"

Student

"What happens if I forget to use the Id annotation"

Teacher

"The application will fail because JPA requires a primary key to manage entities correctly"

Student

"I see now using GeneratedValue makes database operations much easier and safer"

Teacher

"Exactly mastering this concept is essential for building scalable and reliable Spring Boot applications"

Back to Category
Latest Articles
New1
Java
Complete Guide to Java ArrayList add Method: Learn Java Programming Basics for Beginners
Updated
New2
Java
Complete Guide to Java String toString Method: Learn Java Programming Basics for Beginners
Updated
New3
JSP
JSP Comments Explained: How to Write JSP Comments and the Difference from HTML Comments
New
New4
Java
Complete Guide to Java String charAt Method: Learn Java Programming Basics for Beginners
Updated
Popular Articles
No.1
Java&Spring記事人気No1
Thymeleaf
Thymeleaf th:text Complete Guide for Beginners: Displaying Dynamic Text in Spring Boot
No.2
Java&Spring記事人気No2
Spring
Spring Boot and Java Version Compatibility Guide: Spring Boot 3.5 3.4 3.3 with Java 21 and Java 17
No.3
Java&Spring記事人気No3
Spring
Spring Boot with VS Code Setup Guide for Beginners: Extensions, launch.json, and Hot Reload
No.4
Java&Spring記事人気No4
Thymeleaf
How to Use Thymeleaf th:value: A Beginner-Friendly Guide for Spring Boot Forms
No.5
Java&Spring記事人気No5
Thymeleaf
Thymeleaf th:if Complete Guide for Beginners: Conditional Rendering in Spring Boot
No.6
Java&Spring記事人気No6
JSP
JSP Basic Syntax Explained: Scriptlets, Directives, and Expressions for Beginners
No.7
Java&Spring記事人気No7
Java
Java Scanner hasNext Method Complete Guide for Beginners: Checking Input Before Reading Data
No.8
Java&Spring記事人気No8
Spring
Spring Boot @Transactional Annotation Explained: A Beginner's Guide to Database Transactions in Java