0
0
Spring Bootframework~5 mins

@Id and @GeneratedValue for primary keys in Spring Boot

Choose your learning style9 modes available
Introduction

We use @Id to mark a field as the main identifier for a database record. @GeneratedValue helps create unique IDs automatically so we don't have to set them ourselves.

When you want to uniquely identify each record in a database table.
When you want the database or framework to automatically create unique IDs for new records.
When building applications that store data and need to retrieve or update specific entries.
When you want to avoid manually managing primary key values to prevent duplicates.
Syntax
Spring Boot
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;

@Entity
public class EntityName {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    // other fields, getters, setters
}

@Id marks the primary key field.

@GeneratedValue tells Spring Boot to generate the ID automatically. The strategy defines how IDs are created.

Examples
This example uses GenerationType.IDENTITY which lets the database handle ID generation, often using auto-increment.
Spring Boot
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 userId;

    private String name;
}
This example uses GenerationType.SEQUENCE which uses a database sequence to generate IDs, common in some databases like Oracle.
Spring Boot
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long productId;

    private String productName;
}
GenerationType.AUTO lets Spring Boot pick the best strategy based on the database.
Spring Boot
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;

@Entity
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long orderId;

    private String orderDetails;
}
Sample Program

This Spring Boot app defines a Person entity with @Id and @GeneratedValue. It saves a new person and prints the list before and after saving. The ID is generated automatically.

Spring Boot
package com.example.demo;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.beans.factory.annotation.Autowired;

@Entity
class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    public Person() {}

    public Person(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Person{id=" + id + ", name='" + name + "'}";
    }
}

@Repository
interface PersonRepository extends JpaRepository<Person, Long> {}

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    @Autowired
    private PersonRepository personRepository;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Before saving:");
        personRepository.findAll().forEach(System.out::println);

        Person newPerson = new Person("Alice");
        personRepository.save(newPerson);

        System.out.println("After saving:");
        personRepository.findAll().forEach(System.out::println);
    }
}
OutputSuccess
Important Notes

Time complexity: Generating the ID is very fast and handled by the database or framework.

Space complexity: No extra space is needed beyond the entity object.

Common mistake: Forgetting to add @Id causes errors because the framework doesn't know the primary key.

Use @GeneratedValue when you want automatic unique IDs. If you want to set IDs manually, do not use it.

Summary

@Id marks the primary key field in an entity.

@GeneratedValue automatically creates unique IDs for new records.

Choosing the right GenerationType depends on your database and needs.