0
0
Spring Bootframework~30 mins

@Id and @GeneratedValue for primary keys in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @Id and @GeneratedValue for Primary Keys in Spring Boot
📖 Scenario: You are building a simple Spring Boot application to manage a list of books. Each book needs a unique identifier to keep track of it in the database.
🎯 Goal: Create a Book entity class with a primary key field that uses @Id and @GeneratedValue annotations to automatically generate unique IDs for each book.
📋 What You'll Learn
Create a Book class annotated with @Entity
Add a private field id of type Long to serve as the primary key
Annotate the id field with @Id and @GeneratedValue
Use GenerationType.IDENTITY strategy for @GeneratedValue
Add a private field title of type String for the book's title
💡 Why This Matters
🌍 Real World
In real applications, entities need unique IDs to identify records in databases. Using @Id and @GeneratedValue helps automate this process.
💼 Career
Understanding how to define primary keys with auto-generation is essential for backend developers working with Spring Boot and databases.
Progress0 / 4 steps
1
Create the Book entity class with fields
Create a public class called Book annotated with @Entity. Inside it, declare a private Long field named id and a private String field named title.
Spring Boot
Need a hint?

Use @Entity above the class. Declare id and title as private fields inside the class.

2
Add @Id annotation to the id field
Add the @Id annotation above the id field in the Book class to mark it as the primary key.
Spring Boot
Need a hint?

Place @Id directly above the id field.

3
Add @GeneratedValue with IDENTITY strategy
Add the @GeneratedValue annotation above the id field with the strategy set to GenerationType.IDENTITY to let the database generate unique IDs automatically.
Spring Boot
Need a hint?

Use @GeneratedValue(strategy = GenerationType.IDENTITY) above the id field.

4
Add getter and setter methods for id and title
Add public getter and setter methods for both id and title fields in the Book class to allow access and modification.
Spring Boot
Need a hint?

Write simple getter and setter methods for both fields.