Databases with Spring Data JPA
JPA maps Java classes to database tables. Spring Data JPA writes the database code for you: declare an interface, and Spring creates the implementation. We'll use H2, a small database that runs inside your app - perfect for learning.
Spring Data JPA removes most database boilerplate: you define entities (tables) and repository interfaces, and Spring generates the queries. You still need to understand SQL to design tables and check what JPA does.
An entity: one class = one table
Example
import jakarta.persistence.*;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 80)
private String name;
private String category;
private int price;
private int stock;
protected Product() {} // JPA needs an empty constructor
public Product(String name, String category, int price, int stock) {
this.name = name; this.category = category; this.price = price; this.stock = stock;
}
// getters and setters ...
}A repository: no SQL needed for the basics
Example
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findByCategory(String category); // Spring reads the method name
List<Product> findByPriceLessThanOrderByPriceAsc(int maxPrice);
boolean existsByName(String name);
@Query("select p from Product p where p.stock = 0")
List<Product> soldOut();
}You get save, findById, findAll, deleteById, count and more for free. Methods like findByCategory are turned into SQL from their names.
Using it
Example
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductRepository repo;
public ProductController(ProductRepository repo) { this.repo = repo; }
@GetMapping
public List<Product> list(@RequestParam(required = false) String category) {
return category == null ? repo.findAll() : repo.findByCategory(category);
}
@GetMapping("/{id}")
public Product one(@PathVariable long id) {
return repo.findById(id).orElseThrow(() -> new NotFoundException("Product " + id + " not found"));
}
}Example
# application.properties (development)
spring.datasource.url=jdbc:h2:mem:shop
spring.jpa.hibernate.ddl-auto=update # create/update tables from entities (dev only!)
spring.jpa.show-sql=true # print the SQL Spring runs - great for learning
spring.h2.console.enabled=true # browse the data at /h2-consoleFor production use PostgreSQL or MySQL (add the driver dependency and change the URL). Don't use
ddl-auto=update there - manage table changes with a migration tool like Flyway. See the SQL course to understand the queries JPA writes.Key points
- @Entity maps a class to a table.
- JpaRepository gives CRUD methods.
- Derived queries come from method names.
📝 Test yourself
1. What does @Entity mean?
2. How does Spring know what findByCategory should do?
3. Fill in the interface to extend for a repository:
public interface ProductRepository extends <Product, Long> { }
