📖 Scenario: You are building a simple Spring Boot application that manages a list of books. Each book has a title and an author. You will create the data model, configure the database connection, implement the repository to interact with the database, and finally create a REST controller to expose the data.
🎯 Goal: Build a Spring Boot application that connects to an in-memory H2 database, stores book data, and exposes a REST API to retrieve the list of books.
📋 What You'll Learn
Create a Book entity with fields id, title, and author
Configure the application to use H2 in-memory database
Create a Spring Data JPA repository interface for Book
Create a REST controller with a GET endpoint /books to return all books
💡 Why This Matters
🌍 Real World
This project simulates a common real-world scenario where a backend application manages data stored in a database and exposes it via REST APIs for frontend or other services to consume.
💼 Career
Understanding how to orchestrate database entities, repositories, and REST controllers in Spring Boot is essential for backend development roles and building full-stack applications.
Progress0 / 4 steps
1
Create the Book entity
Create a Java class called Book in package com.example.demo with fields Long id, String title, and String author. Annotate it with @Entity. Use @Id and @GeneratedValue on the id field.
Spring Boot
Hint
Use @Entity to mark the class as a database entity. Use @Id and @GeneratedValue on the id field.
2
Configure H2 database in application.properties
Add the following lines to src/main/resources/application.properties to configure the H2 in-memory database and enable the H2 console: spring.datasource.url=jdbc:h2:mem:testdb, spring.datasource.driverClassName=org.h2.Driver, spring.datasource.username=sa, spring.datasource.password=, spring.jpa.database-platform=org.hibernate.dialect.H2Dialect, and spring.h2.console.enabled=true.
Spring Boot
Hint
Configure the H2 database URL and enable the H2 console for easy database access.
3
Create the BookRepository interface
Create an interface called BookRepository in package com.example.demo that extends JpaRepository<Book, Long>. This interface will allow database operations on the Book entity.
Spring Boot
Hint
Extend JpaRepository with the entity Book and primary key type Long.
4
Create the BookController REST API
Create a class called BookController in package com.example.demo. Annotate it with @RestController. Inject BookRepository via constructor. Add a GET mapping for /books that returns List<Book> by calling bookRepository.findAll().
Spring Boot
Hint
Use @RestController and @GetMapping("/books"). Inject the repository via constructor.
Practice
(1/5)
1. What is the main role of a Spring Boot repository in database orchestration?
easy
A. To provide methods for saving, reading, updating, and deleting data
B. To define the database schema manually
C. To handle user interface rendering
D. To manage application security settings
Solution
Step 1: Understand repository purpose
Spring Boot repositories act as a bridge between the app and the database, offering easy data operations.
Step 2: Identify repository capabilities
They provide built-in methods like save(), findById(), delete(), which handle data safely without manual SQL.
Final Answer:
To provide methods for saving, reading, updating, and deleting data -> Option A
Quick Check:
Repository = Data operations [OK]
Hint: Repositories manage data actions like save and find [OK]
Common Mistakes:
Confusing repositories with UI components
Thinking repositories define database schema
Assuming repositories handle security
2. Which of the following is the correct way to declare a Spring Data JPA repository interface for an entity User with primary key type Long?
easy
A. public interface UserRepository extends Repository<User> {}
B. public interface UserRepository extends JpaRepository {}
C. public class UserRepository implements JpaRepository {}
D. public interface UserRepository extends CrudRepository {}
Solution
Step 1: Recall correct interface extension
Spring Data JPA repositories extend JpaRepository to get full CRUD support.
Step 2: Check syntax correctness
public interface UserRepository extends JpaRepository {} correctly extends JpaRepository with User entity and Long ID type; others misuse implements or wrong generics order.
Final Answer:
public interface UserRepository extends JpaRepository {} -> Option B
Quick Check:
JpaRepository syntax [OK]
Hint: Use extends JpaRepository for repositories [OK]
Common Mistakes:
Using implements instead of extends
Swapping generic type order
Extending incomplete Repository interface
3. Given the following Spring Boot repository method call:
Optional<User> user = userRepository.findById(5L);
What will user.isPresent() return if no user with ID 5 exists in the database?
medium
A. true
B. Throws an exception
C. null
D. false
Solution
Step 1: Understand findById return type
findById returns an Optional which is empty if no matching record is found.
Step 2: Check isPresent behavior
isPresent() returns false when Optional is empty, meaning no user found.
Final Answer:
false -> Option D
Quick Check:
Optional empty means isPresent() = false [OK]
Hint: Optional.isPresent() false means no data found [OK]
Common Mistakes:
Assuming isPresent() returns true always
Expecting null instead of Optional
Thinking it throws exception if not found
4. Consider this Spring Boot repository interface:
public interface ProductRepository extends JpaRepository { List<Product> findByName(String name); }
Which of the following issues will cause a runtime error when calling findByName(null)?
medium
A. No error; it returns an empty list
B. Method signature is invalid and won't compile
C. Calling findByName with null returns all products
D. Passing null causes a NullPointerException in query generation
Solution
Step 1: Analyze null parameter in derived queries
Spring Data JPA derived query methods accept null parameters and generate SQL like WHERE name = null, which matches no rows (since NULL = NULL is false).
Step 2: Confirm behavior
No exception is thrown at runtime or compile time; it safely returns an empty list.