In Week 3, we built REST APIs with controllers, DTOs, validation, and CRUD operations.
Now, in Week 4, it’s time to connect your APIs to a real database using Spring Data JPA and Hibernate, and understand entity relationships, queries, and performance best practices.
What is JPA and Hibernate?
JPA (Java Persistence API) is a standard interface for working with relational databases in Java.
Hibernate is the most popular JPA implementation, providing extra features like caching, lazy loading, and advanced queries.
Think of JPA as the contract and Hibernate as the implementation.
Why Use Spring Data JPA?
Spring Data JPA simplifies database access by:
Auto-generating queries
Handling boilerplate CRUD code
Supporting pagination and sorting
Integrating seamlessly with Spring Boot
Step 1: Add Dependencies
In your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Optional: MySQL/PostgreSQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>Start with H2 (in-memory DB) for development. Switch to MySQL/PostgreSQL for production.
Step 2: Configure Database
application.yml example:
spring:
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password:
jpa:
hibernate:
ddl-auto: update
show-sql: true
ddl-auto: updateautomatically creates tables based on your entities. Usevalidatein production.
