Bird
Raised Fist0
Spring Bootframework~20 mins

@Id and @GeneratedValue for primary keys in Spring Boot - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Primary Key Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the effect of @Id annotation in a Spring Boot entity?
In a Spring Boot JPA entity, what does the @Id annotation do?
Spring Boot
import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class User {
    @Id
    private Long userId;
    private String name;
}
AMarks the field as the primary key of the entity in the database.
BAutomatically generates a unique value for the field when saving.
CSpecifies the database table name for the entity.
DIndicates the field should be ignored by JPA.
Attempts:
2 left
💡 Hint
Think about what uniquely identifies each record in a database table.
📝 Syntax
intermediate
2:00remaining
Which @GeneratedValue strategy generates values using a database identity column?
In Spring Boot JPA, which @GeneratedValue strategy uses the database's identity column to generate primary key values?
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.IDENTITY)
    private Long id;
}
AGenerationType.IDENTITY
BGenerationType.SEQUENCE
CGenerationType.TABLE
DGenerationType.AUTO
Attempts:
2 left
💡 Hint
This strategy relies on the database to auto-increment the primary key.
🔧 Debug
advanced
2:00remaining
Why does this entity fail to save with a primary key error?
Given the entity below, why might saving it cause a primary key error?
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.SEQUENCE)
    private Long orderId;

    private String product;
}
AThe @Id annotation is missing from the primary key field.
BThe GenerationType.SEQUENCE strategy is invalid and causes a syntax error.
CThe database does not have a sequence defined for this entity's primary key generation.
DThe entity class is missing the @Table annotation specifying the table name.
Attempts:
2 left
💡 Hint
Check if the database supports sequences or if one is configured.
state_output
advanced
2:00remaining
What is the value of 'id' after saving this entity with GenerationType.AUTO?
Consider this entity saved to the database. What will be the value of id after saving?
Spring Boot
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;

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

    private String name;

    public Long getId() { return id; }
}
AThe value must be manually set before saving; otherwise, it throws an error.
BAlways null because GenerationType.AUTO does not generate values.
CZero because the default value of Long is 0 before saving.
DA unique generated value assigned by the persistence provider after saving.
Attempts:
2 left
💡 Hint
GenerationType.AUTO lets the provider pick the best strategy to generate a unique id.
🧠 Conceptual
expert
2:00remaining
Which statement about @GeneratedValue strategies is true?
Select the only true statement about @GeneratedValue strategies in Spring Boot JPA.
AGenerationType.IDENTITY requires a sequence object in the database to generate keys.
BGenerationType.TABLE uses a separate table to generate unique primary keys and works across all databases.
CGenerationType.SEQUENCE is the default strategy and works without any database setup.
DGenerationType.AUTO disables automatic key generation and requires manual id assignment.
Attempts:
2 left
💡 Hint
Think about which strategy uses a table to generate keys and is database independent.

Practice

(1/5)
1. What is the main purpose of the @Id annotation in a Spring Boot entity?
easy
A. To specify a foreign key relationship
B. To generate unique values automatically
C. To define a database table name
D. To mark the primary key field of the entity

Solution

  1. Step 1: Understand the role of @Id

    The @Id annotation marks a field as the primary key in a database entity.
  2. Step 2: Differentiate from other annotations

    @GeneratedValue generates values, but @Id specifically identifies the primary key field.
  3. Final Answer:

    To mark the primary key field of the entity -> Option D
  4. Quick Check:

    @Id marks primary key [OK]
Hint: Remember: @Id means 'this is the primary key' [OK]
Common Mistakes:
  • Confusing @Id with @GeneratedValue
  • Thinking @Id generates values automatically
  • Using @Id to name tables
2. Which of the following is the correct way to use @GeneratedValue with GenerationType.IDENTITY in a Spring Boot entity?
easy
A. @GeneratedValue(strategy = GenerationType.AUTO)
B. @GeneratedValue(strategy = GenerationType.SEQUENCE)
C. @GeneratedValue(strategy = GenerationType.IDENTITY)
D. @GeneratedValue(strategy = GenerationType.TABLE)

Solution

  1. Step 1: Identify the correct strategy for identity generation

    GenerationType.IDENTITY is used to let the database auto-increment the primary key.
  2. Step 2: Match the annotation syntax

    The correct syntax is @GeneratedValue(strategy = GenerationType.IDENTITY).
  3. Final Answer:

    @GeneratedValue(strategy = GenerationType.IDENTITY) -> Option C
  4. Quick Check:

    Use GenerationType.IDENTITY with strategy = GenerationType.IDENTITY [OK]
Hint: Use strategy = GenerationType.IDENTITY for auto-increment keys [OK]
Common Mistakes:
  • Using AUTO instead of IDENTITY for auto-increment
  • Omitting the strategy parameter
  • Confusing SEQUENCE with IDENTITY
3. Given the entity code below, what will be the value of user.getId() after saving a new user to the database?
 @Entity
 public class User {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;
   private String name;

   // getters and setters
 }
medium
A. A unique auto-generated Long value
B. null
C. The name of the user
D. An exception will be thrown

Solution

  1. Step 1: Understand @GeneratedValue with IDENTITY

    This strategy lets the database generate a unique primary key value automatically when saving.
  2. Step 2: Predict the value after saving

    After saving, user.getId() will hold the generated unique Long value assigned by the database.
  3. Final Answer:

    A unique auto-generated Long value -> Option A
  4. Quick Check:

    @GeneratedValue with IDENTITY creates unique IDs [OK]
Hint: After save, IDENTITY generates a unique Long ID automatically [OK]
Common Mistakes:
  • Expecting id to be null after save
  • Confusing id with other fields
  • Assuming an error occurs without database setup
4. Consider this entity code snippet:
 @Entity
 public class Product {
   @Id
   @GeneratedValue
   private Long productId;

   private String name;
 }

What is the likely problem with this code?
medium
A. Missing strategy in @GeneratedValue may cause unexpected ID generation
B. The field productId should not be private
C. The @Id annotation is missing
D. The entity class must implement Serializable

Solution

  1. Step 1: Check @GeneratedValue usage

    The @GeneratedValue annotation without specifying a strategy defaults to AUTO, which may behave differently depending on the database.
  2. Step 2: Understand impact of missing strategy

    This can cause unexpected ID generation behavior if the database does not support the default strategy well.
  3. Final Answer:

    Missing strategy in @GeneratedValue may cause unexpected ID generation -> Option A
  4. Quick Check:

    Always specify strategy to avoid surprises [OK]
Hint: Always specify strategy in @GeneratedValue to avoid surprises [OK]
Common Mistakes:
  • Thinking private fields cause errors
  • Believing @Id is missing
  • Assuming Serializable is mandatory
5. You want to create a Spring Boot entity with a primary key that uses a database sequence named user_seq. Which is the correct way to annotate the ID field?
hard
A. @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
B. @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq") @SequenceGenerator(name = "user_seq", sequenceName = "user_seq", allocationSize = 1)
C. @Id @GeneratedValue(strategy = GenerationType.TABLE)
D. @Id @GeneratedValue(strategy = GenerationType.AUTO)

Solution

  1. Step 1: Identify sequence generation requirements

    Using a database sequence requires GenerationType.SEQUENCE and a matching @SequenceGenerator annotation.
  2. Step 2: Match annotations to sequence name

    The @SequenceGenerator defines the sequence name and allocation size, linked by the generator name in @GeneratedValue.
  3. Final Answer:

    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq") @SequenceGenerator(name = "user_seq", sequenceName = "user_seq", allocationSize = 1) -> Option B
  4. Quick Check:

    Use SEQUENCE with @SequenceGenerator for DB sequences [OK]
Hint: Use @SequenceGenerator with SEQUENCE strategy for DB sequences [OK]
Common Mistakes:
  • Using IDENTITY instead of SEQUENCE for sequences
  • Omitting @SequenceGenerator annotation
  • Confusing TABLE and AUTO strategies