Week 5 Day 1 — Spring Data JPA Mental Model
Goal
Today I want to understand the mental model of Spring Data JPA.
Main questions:
- What problem does Spring Data JPA solve?
- What is JPA?
- What is Hibernate?
- What is Spring Data JPA?
- What is an entity?
- What is a repository?
- What is
JpaRepository? - What is
EntityManager? - What is the database access flow in a Spring Boot app?
- What are common exam traps?
1. Quick Review from Week 4
In Week 4, I learned:
- Spring MVC maps HTTP requests to Java controller methods.
- Controllers should usually be thin.
- Services contain business logic.
- DTOs define the API contract.
- REST APIs should usually not expose JPA entities directly.
@Validvalidates request DTOs.@RestControllerAdvicehandles errors globally.
Memory sentence:
Controller handles HTTP.
Service handles business logic.
Repository handles persistence.
Today I start the repository and persistence layer.
2. The Big Backend Layer Picture
A typical Spring Boot REST API has layers:
Controller
↓
Service
↓
Repository
↓
Database
Example:
HTTP request
↓
TaskController
↓
TaskService
↓
TaskRepository
↓
PostgreSQL
Memory sentence:
Controllers talk to services. Services talk to repositories. Repositories talk to the database.
3. What Problem Does Spring Data JPA Solve?
Without Spring Data JPA, I might write a lot of repetitive database code.
Example repetitive tasks:
open database connection
write SQL
map result rows to Java objects
save objects
update objects
delete objects
handle transactions
handle exceptions
close resources
Spring Data JPA helps reduce boilerplate.
It lets me write repository interfaces like:
public interface TaskRepository extends JpaRepository<TaskEntity, Long> {
}
and automatically gives me methods like:
save()
findById()
findAll()
deleteById()
existsById()
count()
Memory sentence:
Spring Data JPA reduces repetitive database access code.
4. What Is JPA?
JPA means:
Java Persistence API
Simple definition:
JPA is a Java specification for mapping Java objects to relational database tables.
JPA defines concepts like:
@Entity
@Id
@Table
@Column
@ManyToOne
@OneToMany
EntityManager
JPQL
transactions
persistence context
Important:
JPA is a specification, not the implementation itself.
Memory sentence:
JPA defines the rules for object-relational mapping in Java.
5. What Is Hibernate?
Hibernate is a JPA implementation.
Simple definition:
Hibernate is the most common implementation of JPA.
If JPA is the rulebook, Hibernate is the engine that follows the rulebook.
Mental model:
JPA = interface/specification
Hibernate = implementation/provider
Example:
JPA defines:
@Entity
Hibernate understands this annotation and maps the class to a table.
Memory sentence:
JPA defines. Hibernate implements.
6. What Is Spring Data JPA?
Spring Data JPA is a Spring project that makes JPA easier to use.
It builds on top of JPA.
It gives repository abstractions.
Simple definition:
Spring Data JPA provides repository interfaces and query support on top of JPA.
With Spring Data JPA, I can write:
public interface UserRepository extends JpaRepository<UserEntity, Long> {
Optional<UserEntity> findByEmail(String email);
}
Spring automatically implements this repository at runtime.
Memory sentence:
Spring Data JPA makes JPA easier by generating repository implementations.
7. JPA vs Hibernate vs Spring Data JPA
| Concept | Meaning |
|---|---|
| JPA | Java specification for persistence |
| Hibernate | implementation of JPA |
| Spring Data JPA | Spring repository abstraction on top of JPA |
Memory:
JPA = rules
Hibernate = engine
Spring Data JPA = repository convenience
Example flow:
My repository method
↓
Spring Data JPA
↓
JPA EntityManager
↓
Hibernate
↓
SQL
↓
Database
8. Required Dependency
Gradle:
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
For PostgreSQL:
runtimeOnly("org.postgresql:postgresql")
Example:
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
runtimeOnly("org.postgresql:postgresql")
}
Important:
The JPA starter gives JPA/Hibernate/Spring Data support.
The database driver connects to the specific database.
Memory sentence:
JPA starter is not the same as database driver.
9. Basic Configuration
Example application.yml:
spring:
datasource:
url: jdbc:postgresql://localhost:5432/app
username: postgres
password: postgres
jpa:
hibernate:
ddl-auto: validate
show-sql: true
Important properties:
spring.datasource.url
spring.datasource.username
spring.datasource.password
spring.jpa.hibernate.ddl-auto
spring.jpa.show-sql
In real production projects, passwords should come from environment variables or secret management, not committed YAML.
10. What Is an Entity?
An entity is a Java class mapped to a database table.
Example:
@Entity
@Table(name = "tasks")
public class TaskEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String status;
protected TaskEntity() {
}
public TaskEntity(String title, String status) {
this.title = title;
this.status = status;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public String getStatus() {
return status;
}
}
This class maps to table:
tasks
Memory sentence:
An entity is a Java object that represents a database row.
11. Entity and Table
Entity:
@Entity
@Table(name = "tasks")
public class TaskEntity {
}
Database table:
CREATE TABLE tasks (
id BIGSERIAL PRIMARY KEY,
title VARCHAR(255),
status VARCHAR(50)
);
Mapping:
TaskEntity -> tasks table
id -> id column
title -> title column
status -> status column
12. @Entity
@Entity tells JPA:
This class should be managed as a persistent entity.
Example:
@Entity
public class UserEntity {
}
Without @Entity, JPA does not treat the class as a database entity.
Important:
@Entity classes are managed by JPA, not automatically by Spring as normal beans.
This is an exam trap.
Memory sentence:
@Entitymeans JPA-managed persistence class, not Spring service bean.
13. @Table
@Table customizes the database table name.
Example:
@Entity
@Table(name = "app_users")
public class UserEntity {
}
If I do not use @Table, JPA uses a default table name based on the class name.
But in real projects, explicit table names are often clearer.
14. @Id
Every entity needs an identifier.
Example:
@Id
private Long id;
@Id marks the primary key.
Without an ID, JPA cannot manage the entity properly.
Memory sentence:
Every JPA entity needs an
@Id.
15. @GeneratedValue
@GeneratedValue tells JPA that the ID is generated.
Example:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Common strategies:
IDENTITY
SEQUENCE
AUTO
TABLE
For PostgreSQL, SEQUENCE is common.
For simple examples, IDENTITY is easy to understand.
Memory sentence:
@GeneratedValuemeans the database or provider generates the ID.
16. Protected No-Args Constructor
JPA entities need a no-args constructor.
Example:
protected TaskEntity() {
}
Why?
JPA needs to create entity instances using reflection.
It can be:
protected
public
Protected is often preferred to prevent accidental direct use while still allowing JPA.
Memory sentence:
JPA entities need a no-args constructor.
17. Entity Fields and Columns
By default, fields map to columns.
Example:
private String title;
maps to a column like:
title
Customize with @Column:
@Column(name = "task_title", nullable = false, length = 120)
private String title;
Meaning:
column name = task_title
not nullable
max length = 120
18. Entity vs DTO
Entity:
@Entity
@Table(name = "tasks")
public class TaskEntity {
@Id
private Long id;
private String title;
private String status;
}
DTO:
public record TaskDto(
Long id,
String title,
String status
) {
}
Difference:
| Entity | DTO |
|---|---|
| Maps to database table | Defines API data |
| Used by repository/JPA | Used by controller/API |
| Persistence model | Transfer model |
| May contain relationships/lazy loading | Should be API-safe |
| Should not usually be exposed directly | Good for REST responses |
Memory sentence:
Entity is for database. DTO is for API.
19. What Is a Repository?
A repository is an object that provides access to persistent data.
Simple definition:
A repository hides database access behind an interface.
Example:
public interface TaskRepository extends JpaRepository<TaskEntity, Long> {
}
This repository works with:
TaskEntity
and its ID type:
Long
Memory sentence:
Repository is the persistence access layer.
20. JpaRepository
JpaRepository is a Spring Data interface with many ready-made methods.
Example:
public interface TaskRepository extends JpaRepository<TaskEntity, Long> {
}
It gives methods like:
save(entity)
findById(id)
findAll()
delete(entity)
deleteById(id)
existsById(id)
count()
flush()
So I do not need to implement basic CRUD manually.
21. Repository Type Parameters
JpaRepository<TaskEntity, Long>
means:
TaskEntity = entity type
Long = ID type
If the ID is UUID:
public interface TaskRepository extends JpaRepository<TaskEntity, UUID> {
}
Memory sentence:
JpaRepository<EntityType, IdType>.
22. Repository Is a Spring Bean
This interface:
public interface TaskRepository extends JpaRepository<TaskEntity, Long> {
}
becomes a Spring bean.
So I can inject it:
@Service
public class TaskService {
private final TaskRepository taskRepository;
public TaskService(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
}
Spring Data JPA creates a proxy implementation at runtime.
Memory sentence:
Spring Data creates repository implementation proxies automatically.
23. Repository Proxy
I write:
public interface TaskRepository extends JpaRepository<TaskEntity, Long> {
}
Spring creates:
runtime proxy implementation
This proxy handles calls like:
taskRepository.findById(1L);
Behind the scenes, it uses JPA and EntityManager.
Memory sentence:
I write the repository interface. Spring Data provides the implementation.
24. What Is EntityManager?
EntityManager is the core JPA interface for interacting with the persistence context.
Simple definition:
EntityManagermanages JPA entities and communicates with the database through the JPA provider.
It can:
persist entities
find entities
merge entities
remove entities
create queries
manage persistence context
flush changes
Example:
entityManager.find(TaskEntity.class, 1L);
But with Spring Data JPA, I often use repositories instead of using EntityManager directly.
Memory sentence:
Repository is the common Spring Data interface. EntityManager is the core JPA API underneath.
25. Repository vs EntityManager
| Topic | Repository | EntityManager |
|---|---|---|
| Level | higher-level Spring Data abstraction | lower-level JPA API |
| Common use | normal CRUD and queries | custom persistence logic |
| Code style | interface methods | explicit JPA operations |
| Implementation | generated proxy | JPA provider implementation |
| Beginner use | very common | less common directly |
Memory sentence:
Use repositories for common data access. Use EntityManager for lower-level custom cases.
26. Database Access Flow
Example request:
GET /api/tasks/1
Flow:
1. Client sends GET /api/tasks/1.
2. DispatcherServlet receives request.
3. TaskController.getTask(1) is called.
4. Controller calls TaskService.findById(1).
5. Service calls TaskRepository.findById(1).
6. Repository proxy uses EntityManager.
7. EntityManager uses Hibernate.
8. Hibernate generates SQL.
9. Database returns row.
10. Hibernate maps row to TaskEntity.
11. Service maps TaskEntity to TaskDto.
12. Controller returns TaskDto.
13. Jackson converts TaskDto to JSON.
Short memory:
Controller -> Service -> Repository -> EntityManager -> Hibernate -> Database
27. Full Example: Entity
@Entity
@Table(name = "tasks")
public class TaskEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String title;
@Column(nullable = false)
private String status;
protected TaskEntity() {
}
public TaskEntity(String title, String status) {
this.title = title;
this.status = status;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public String getStatus() {
return status;
}
public void complete() {
this.status = "DONE";
}
}
Important:
Entity contains persistence data and domain behavior.
28. Full Example: Repository
public interface TaskRepository extends JpaRepository<TaskEntity, Long> {
List<TaskEntity> findByStatus(String status);
Optional<TaskEntity> findByTitle(String title);
boolean existsByTitle(String title);
}
Spring Data JPA creates queries from method names.
Examples:
findByStatus -> WHERE status = ?
findByTitle -> WHERE title = ?
existsByTitle -> checks existence by title
We will study derived queries in detail later.
29. Full Example: Service
@Service
public class TaskService {
private final TaskRepository taskRepository;
public TaskService(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
public TaskDto findById(Long id) {
TaskEntity task = taskRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Task", id));
return toDto(task);
}
public TaskDto create(CreateTaskRequest request) {
TaskEntity task = new TaskEntity(
request.title(),
"OPEN"
);
TaskEntity saved = taskRepository.save(task);
return toDto(saved);
}
private TaskDto toDto(TaskEntity entity) {
return new TaskDto(
entity.getId(),
entity.getTitle(),
entity.getStatus()
);
}
}
Service responsibilities:
business logic
transaction boundary
repository coordination
entity-to-DTO mapping
exception decisions
30. Full Example: Controller
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
private final TaskService taskService;
public TaskController(TaskService taskService) {
this.taskService = taskService;
}
@GetMapping("/{id}")
public TaskDto get(@PathVariable Long id) {
return taskService.findById(id);
}
@PostMapping
public ResponseEntity<TaskDto> create(
@Valid @RequestBody CreateTaskRequest request
) {
TaskDto created = taskService.create(request);
URI location = URI.create("/api/tasks/" + created.id());
return ResponseEntity.created(location).body(created);
}
}
Controller responsibilities:
HTTP mapping
request reading
validation trigger
status codes
delegation to service
31. Full Example: DTOs
public record CreateTaskRequest(
@NotBlank
@Size(max = 100)
String title
) {
}
public record TaskDto(
Long id,
String title,
String status
) {
}
Request DTO:
what client sends
Response DTO:
what server returns
Entity:
what database stores
Memory sentence:
Request DTO, entity, and response DTO are different models with different jobs.
32. What Happens with save()?
Example:
TaskEntity task = new TaskEntity("Learn JPA", "OPEN");
TaskEntity saved = taskRepository.save(task);
For a new entity:
JPA inserts a new row.
For an existing managed entity:
JPA updates the row when the transaction flushes.
Important:
save() does not always mean immediate SQL at that exact line.
SQL execution can happen when:
transaction commits
flush happens
query requires flush
repository flush method is called
We will study this more in transactions.
33. Optional from findById
findById returns:
Optional<TaskEntity>
Example:
TaskEntity task = taskRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Task", id));
Why Optional?
The row may not exist.
Do not do:
taskRepository.findById(id).get();
because it can throw NoSuchElementException.
Better:
orElseThrow(...)
Memory sentence:
findByIdreturns Optional because the entity may not exist.
34. @Repository
Spring Data repository interfaces do not always need @Repository.
Example:
public interface TaskRepository extends JpaRepository<TaskEntity, Long> {
}
Spring Data detects it and creates a bean.
For custom repository classes, @Repository can be used.
Important concept:
@Repository marks persistence components and supports exception translation.
Memory sentence:
Spring Data repositories are detected automatically.
@Repositoryis still the persistence stereotype.
35. Exception Translation
Spring can translate persistence exceptions into Spring’s DataAccessException hierarchy.
Example:
database-specific exception
↓
Spring DataAccessException
Why useful?
consistent exception model
less database-provider-specific code
@Repository is associated with this persistence exception translation concept.
For certification:
Know that
@Repositoryis a persistence stereotype and participates in exception translation.
36. Entity Is Not a Spring Bean
This is important.
@Service:
@Service
public class TaskService {
}
This is a Spring bean.
@Entity:
@Entity
public class TaskEntity {
}
This is a JPA entity.
It is not a normal singleton Spring bean.
Do not inject services into entities like this:
@Entity
public class TaskEntity {
@Autowired
private EmailService emailService;
}
Bad idea.
Entities should usually not depend on Spring services.
Memory sentence:
Spring beans are managed by Spring. Entities are managed by JPA.
37. Entity Lifecycle vs Bean Lifecycle
Spring bean lifecycle:
created by Spring container
dependencies injected
@PostConstruct
used as singleton/prototype/etc.
destroy callbacks
JPA entity lifecycle:
new/transient
managed/persistent
detached
removed
Different worlds.
Memory sentence:
Bean lifecycle and entity lifecycle are not the same.
We will study entity lifecycle more later.
38. ddl-auto
Spring Boot property:
spring:
jpa:
hibernate:
ddl-auto: validate
Common values:
none
validate
update
create
create-drop
Meaning:
| Value | Meaning |
|---|---|
none | do not manage schema |
validate | validate schema matches entities |
update | try to update schema |
create | drop and create schema on startup |
create-drop | create on startup, drop on shutdown |
Production caution:
Avoid create/create-drop/update in production unless you know exactly what you are doing.
In production, use migrations:
Flyway
Liquibase
Memory sentence:
Use migrations for real schema changes.
39. Repository Method Names
Spring Data JPA can create queries from method names.
Example:
List<TaskEntity> findByStatus(String status);
means:
SELECT * FROM tasks WHERE status = ?
Concept examples:
Optional<UserEntity> findByEmail(String email);
boolean existsByEmail(String email);
List<TaskEntity> findByStatusOrderByTitleAsc(String status);
List<TaskEntity> findByTitleContainingIgnoreCase(String keyword);
We will go deeper in the next lesson.
Memory sentence:
Spring Data can derive queries from repository method names.
40. Custom Query with @Query
Sometimes method names become too long.
Then use @Query.
Example JPQL:
@Query("select t from TaskEntity t where t.status = :status")
List<TaskEntity> findTasksByStatus(@Param("status") String status);
JPQL uses entity names and fields, not table names and columns.
SQL uses table names and columns.
Memory sentence:
JPQL talks about entities. SQL talks about tables.
41. Repository Return Types
Common return types:
Optional<TaskEntity>
List<TaskEntity>
Page<TaskEntity>
Slice<TaskEntity>
boolean
long
void
Examples:
Optional<TaskEntity> findById(Long id);
List<TaskEntity> findByStatus(String status);
boolean existsByTitle(String title);
long countByStatus(String status);
We will study pagination later.
42. Common CRUD Methods
| Method | Meaning |
|---|---|
save(entity) | insert or update entity |
findById(id) | find one entity by ID |
findAll() | find all entities |
delete(entity) | delete entity |
deleteById(id) | delete by ID |
existsById(id) | check existence |
count() | count rows |
Important:
Repository methods work with entities, not DTOs by default.
43. Why Services Should Use Repositories
Bad:
@RestController
public class TaskController {
private final TaskRepository taskRepository;
@GetMapping("/api/tasks/{id}")
public TaskEntity get(@PathVariable Long id) {
return taskRepository.findById(id).orElseThrow();
}
}
Problems:
controller talks directly to database layer
business logic may move into controller
entities exposed directly
harder to test
less separation of concerns
Better:
Controller -> Service -> Repository
Memory sentence:
Controllers should not usually call repositories directly in real applications.
44. Where Should Mapping Happen?
Common styles:
service maps entity to DTO
dedicated mapper maps entity to DTO
repository returns projections in special cases
Simple style for learning:
private TaskDto toDto(TaskEntity entity) {
return new TaskDto(
entity.getId(),
entity.getTitle(),
entity.getStatus()
);
}
Keep mapping explicit at first.
Memory sentence:
Convert entities to DTOs before returning from API.
45. Common Exam Traps
Trap 1
JPA is not the same as Hibernate.
JPA = specification
Hibernate = implementation
Trap 2
Spring Data JPA is not the same as JPA.
Spring Data JPA = repository abstraction on top of JPA
Trap 3
@Entity does not make a class a Spring bean.
@Entity = JPA-managed
@Service/@Component = Spring-managed
Trap 4
Every entity needs an @Id.
Trap 5
JPA entities need a no-args constructor.
Trap 6
Repository works with entities, not DTOs by default.
Trap 7
JpaRepository<TaskEntity, Long> means entity type and ID type.
Trap 8
Spring Data creates repository implementations automatically.
Trap 9
findById returns Optional because the row may not exist.
Trap 10
Do not expose entities directly from REST controllers in most real projects.
Trap 11
ddl-auto=update is not a replacement for real migrations in production.
Trap 12
JPQL uses entity names and fields, not table names and columns.
46. Real Exam Question: JPA
Question:
What is JPA?
Answer:
JPA is the Java Persistence API. It is a Java specification for mapping Java objects to relational database tables and managing persistence.
47. Real Exam Question: Hibernate
Question:
What is Hibernate?
Answer:
Hibernate is a JPA implementation. It provides the actual persistence engine that maps entities to database tables and executes SQL.
48. Real Exam Question: Spring Data JPA
Question:
What is Spring Data JPA?
Answer:
Spring Data JPA is a Spring project that provides repository abstractions and query support on top of JPA. It reduces boilerplate database access code by generating repository implementations automatically.
49. Real Exam Question: Entity
Question:
What is a JPA entity?
Answer:
A JPA entity is a Java class mapped to a database table. Each entity instance usually represents a row in that table.
50. Real Exam Question: Repository
Question:
What is a repository?
Answer:
A repository is a persistence access abstraction that hides database access behind an interface.
51. Real Exam Question: JpaRepository
Question:
What does JpaRepository<TaskEntity, Long> mean?
Answer:
It means the repository manages TaskEntity objects and their ID type is Long.
52. Real Exam Question: EntityManager
Question:
What is EntityManager?
Answer:
EntityManager is the core JPA interface that manages entity instances and interacts with the persistence context and database through the JPA provider.
53. Real Exam Question: Entity vs Spring Bean
Question:
Is an @Entity a Spring bean?
Answer:
No. An @Entity is managed by JPA as a persistence object. It is not a normal Spring bean like @Service or @Component.
54. Real Exam Question: findById
Question:
Why does findById return Optional?
Answer:
Because the entity with that ID may not exist.
55. Real Exam Question: DTO vs Entity
Question:
Why should REST APIs usually return DTOs instead of entities?
Answer:
DTOs avoid exposing internal database structure, prevent sensitive field leaks, avoid lazy loading and serialization problems, and keep the API contract separate from the persistence model.
56. Interview Answer
Question:
Explain the difference between JPA, Hibernate, and Spring Data JPA.
Good answer:
JPA is the Java specification for persistence and object-relational mapping. Hibernate is a common implementation of that specification. Spring Data JPA is a Spring abstraction on top of JPA that provides repository interfaces, generated implementations, derived queries, and integration with Spring. In short: JPA defines the rules, Hibernate implements them, and Spring Data JPA makes them easier to use.
57. Interview Answer
Question:
What is a JPA entity?
Good answer:
A JPA entity is a Java class mapped to a relational database table. It is annotated with @Entity, has an identifier marked with @Id, and usually has a no-args constructor for JPA. Each entity instance usually represents one row in the table. Entities are managed by JPA, not as normal singleton Spring beans.
58. Interview Answer
Question:
What is a Spring Data repository?
Good answer:
A Spring Data repository is an interface that provides database access methods for an entity. For example, an interface extending JpaRepository<TaskEntity, Long> automatically gets methods such as save, findById, findAll, and deleteById. Spring Data creates a runtime proxy implementation, so I usually do not write the implementation manually.
59. Interview Answer
Question:
What is
EntityManagerand do you use it directly?
Good answer:
EntityManager is the core JPA interface for managing entities and interacting with the persistence context. It can persist, find, merge, remove entities, and create queries. In normal Spring Data JPA applications, I usually use repositories for common data access. I use EntityManager directly only for lower-level or custom persistence cases.
60. Interview Answer
Question:
Explain the database access flow in a Spring Boot REST API.
Good answer:
A request first reaches the controller through Spring MVC. The controller delegates to a service. The service contains business logic and calls a Spring Data JPA repository. The repository is a proxy generated by Spring Data and uses JPA’s EntityManager underneath. The JPA provider, usually Hibernate, generates SQL and talks to the database. The result is mapped to an entity, then usually converted to a DTO before returning to the controller.
61. Tiny Code Practice
Create entity:
@Entity
@Table(name = "tasks")
public class TaskEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String title;
@Column(nullable = false)
private String status;
protected TaskEntity() {
}
public TaskEntity(String title, String status) {
this.title = title;
this.status = status;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public String getStatus() {
return status;
}
}
Create repository:
public interface TaskRepository extends JpaRepository<TaskEntity, Long> {
}
Questions:
- Which annotation makes the class a JPA entity?
- Which annotation marks the primary key?
- Why is the no-args constructor needed?
- What does
JpaRepository<TaskEntity, Long>mean? - Who creates the repository implementation?
Answers:
@Entity@Id- JPA needs it to create entity instances.
- Repository manages
TaskEntitywith ID typeLong. - Spring Data JPA creates a runtime proxy implementation.
62. Tiny Bug Practice 1
Problem:
@Entity
public class TaskEntity {
private Long id;
private String title;
}
Question:
What is missing?
Answer:
@Id is missing. Every JPA entity needs an identifier.
Fix:
@Id
private Long id;
63. Tiny Bug Practice 2
Problem:
@Entity
public class TaskEntity {
@Id
private Long id;
public TaskEntity(String title) {
this.title = title;
}
private String title;
}
Question:
What is missing?
Answer:
A no-args constructor is missing. JPA needs it.
Fix:
protected TaskEntity() {
}
64. Tiny Bug Practice 3
Problem:
@Entity
public class TaskEntity {
@Autowired
private EmailService emailService;
}
Question:
What is wrong?
Answer:
Entities are managed by JPA, not as normal Spring beans. Do not inject Spring services into entities. Business operations that need services should usually be handled in the service layer.
Practice Questions and Answers
Question 1
What problem does Spring Data JPA solve?
Answer:
Spring Data JPA reduces repetitive database access code by providing repository abstractions and automatically generated repository implementations.
Question 2
What is JPA?
Answer:
JPA is the Java Persistence API, a Java specification for mapping Java objects to relational database tables and managing persistence.
Question 3
What is Hibernate?
Answer:
Hibernate is a common implementation of the JPA specification.
Question 4
What is Spring Data JPA?
Answer:
Spring Data JPA is a Spring project that provides repository abstractions and query support on top of JPA.
Question 5
What is the difference between JPA, Hibernate, and Spring Data JPA?
Answer:
JPA is the specification. Hibernate is an implementation of that specification. Spring Data JPA is a Spring abstraction that makes JPA easier to use through repositories.
Question 6
Which dependency adds Spring Data JPA support?
Answer:
Use:
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
Question 7
Do I still need a database driver?
Answer:
Yes. I still need a database driver such as PostgreSQL, MySQL, or MariaDB.
Question 8
What is an entity?
Answer:
An entity is a Java class mapped to a database table. Each entity instance usually represents a row.
Question 9
What does @Entity do?
Answer:
@Entity tells JPA that the class is a persistent entity.
Question 10
What does @Id do?
Answer:
@Id marks the primary key of the entity.
Question 11
Why does a JPA entity need a no-args constructor?
Answer:
JPA needs a no-args constructor to create entity instances using reflection.
Question 12
What is a repository?
Answer:
A repository is a persistence access abstraction that hides database access behind an interface.
Question 13
What does JpaRepository<TaskEntity, Long> mean?
Answer:
It means the repository manages TaskEntity objects and their ID type is Long.
Question 14
Who creates the repository implementation?
Answer:
Spring Data JPA creates a runtime proxy implementation automatically.
Question 15
What is EntityManager?
Answer:
EntityManager is the core JPA interface for managing entities and interacting with the persistence context and database through the JPA provider.
Question 16
What is the difference between repository and EntityManager?
Answer:
A repository is a higher-level Spring Data abstraction for common data access. EntityManager is the lower-level JPA API underneath.
Question 17
What is the database access flow from controller to database?
Answer:
The flow is: Controller calls Service, Service calls Repository, Repository uses EntityManager, EntityManager uses Hibernate, Hibernate generates SQL and talks to the database.
Question 18
Why does findById return Optional?
Answer:
Because the entity with that ID may not exist.
Question 19
Is an entity a Spring bean?
Answer:
No. An entity is managed by JPA, not as a normal singleton Spring bean.
Question 20
Why should REST APIs usually return DTOs instead of entities?
Answer:
DTOs avoid exposing internal database structure, sensitive fields, lazy loading issues, and serialization problems. They keep the API contract separate from the persistence model.
Final Memory Sentences
- Spring Data JPA reduces database boilerplate.
- JPA is the persistence specification.
- Hibernate is a JPA implementation.
- Spring Data JPA is a repository abstraction on top of JPA.
- JPA defines, Hibernate implements, Spring Data JPA simplifies.
spring-boot-starter-data-jpaadds JPA support.- A database driver is still needed.
- An entity is a Java class mapped to a database table.
- Every entity needs
@Entityand@Id. - JPA entities need a no-args constructor.
- Entity is for database. DTO is for API.
- Repository hides database access.
JpaRepository<Entity, Id>defines entity type and ID type.- Spring Data creates repository proxy implementations.
EntityManageris the core JPA API underneath.- Database flow: Controller -> Service -> Repository -> EntityManager -> Hibernate -> Database.
findByIdreturns Optional because the row may not exist.@Entityis not a Spring bean.- Do not inject services into entities.
- Use migrations for real production schema changes.