Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SB
Spring Boot
0/10 completed
Beginner
Spring Boot setupControllers and RESTBeans and dependency injection
Intermediate
Spring Data JPAValidation and error handlingTesting Spring Boot apps
Advanced
Spring SecurityRelationships, paging and migrationsMicroservices with Spring
Pro
Production-ready Spring Boot
Tracks / Spring Boot / Intermediate

Spring Data JPA

Most backends store data in a relational database. JPA (Jakarta Persistence) maps Java classes to tables, Hibernate is the implementation that generates the SQL, and Spring Data JPA removes the remaining boilerplate: you write an interface, and Spring implements the repository for you, even generating queries from method names.

Entities

An entity is a class mapped to a table:

java
import jakarta.persistence.*;
import java.math.BigDecimal;

@Entity
public class Product {

    @Id
    @GeneratedValue
    private Long id;

    @Column(nullable = false, length = 100)
    private String name;

    @Column(nullable = false, precision = 10, scale = 2)
    private BigDecimal price;          // never double for money

    private int stock;

    private String category;

    protected Product() {}             // JPA needs a no-argument constructor

    public Product(String name, BigDecimal price, int stock, String category) {
        this.name = name;
        this.price = price;
        this.stock = stock;
        this.category = category;
    }

    public Long getId() { return id; }
    public String getName() { return name; }
    // … other getters and setters
}
Annotation Meaning
@Entity This class is a table (named product by default)
@Id, @GeneratedValue The primary key, generated by the database
@Column(nullable = false, length = 100) Column constraints
@Table(name = "orders") A custom table name
@Enumerated(EnumType.STRING) Store an enum by name (never by position)
@ManyToOne, @OneToMany Relationships (next lessons)

Entities are regular classes rather than records, because JPA needs to create them empty and change their fields.

Repositories

java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface ProductRepository extends JpaRepository<Product, Long> {

    List<Product> findByCategoryOrderByPriceAsc(String category);

    List<Product> findByPriceLessThan(BigDecimal max);

    List<Product> findByNameContainingIgnoreCase(String text);

    boolean existsByNameIgnoreCase(String name);

    @Query("select p from Product p where p.stock = 0")
    List<Product> findSoldOut();
}

That's the whole repository. By extending JpaRepository<Product, Long> you inherit save, saveAll, findById, findAll, count, existsById, delete, deleteById, paging and sorting. Spring generates an implementation at startup.

Derived queries

Spring parses method names into queries:

Method Generated condition
findByCategory(String c) where category = ?
findByPriceLessThan(BigDecimal p) where price < ?
findByPriceBetween(a, b) where price between ? and ?
findByNameContainingIgnoreCase(s) where upper(name) like upper('%' + ? + '%')
findByCategoryAndStockGreaterThan(c, n) where category = ? and stock > ?
findTop3ByOrderByPriceDesc() the 3 most expensive
countByCategory(c), existsByName(n), deleteByCategory(c) counts, existence checks, deletes

For anything more complex, write JPQL (queries over entities, not tables) with @Query, or native SQL with @Query(value = "…", nativeQuery = true).

Using the repository in a service

java
@Service
@Transactional(readOnly = true)
public class ProductService {

    private final ProductRepository products;

    public ProductService(ProductRepository products) {
        this.products = products;
    }

    public List<Product> findAll(String category) {
        return category == null ? products.findAll() : products.findByCategoryOrderByPriceAsc(category);
    }

    public Product findById(Long id) {
        return products.findById(id).orElseThrow(() -> new ProductNotFoundException(id));
    }

    @Transactional
    public Product create(ProductRequest request) {
        return products.save(new Product(request.name(), request.price(), request.stock(), request.category()));
    }

    @Transactional
    public Product update(Long id, ProductRequest request) {
        Product product = findById(id);
        product.setName(request.name());
        product.setPrice(request.price());
        product.setStock(request.stock());
        product.setCategory(request.category());
        return product;               // no save() needed: changes are flushed when the transaction commits
    }

    @Transactional
    public void delete(Long id) {
        products.delete(findById(id));
    }
}

Transactions

@Transactional wraps a method in a database transaction: everything inside commits together, or rolls back together if a RuntimeException is thrown. Inside a transaction, entities loaded from the database are managed: Hibernate tracks changes and writes them at commit (dirty checking), which is why update never calls save.

Put @Transactional on service methods, which define units of business work. readOnly = true for queries lets Hibernate skip change tracking.

Configuring the database

With H2 on the classpath, Spring Boot creates an in-memory database automatically, ideal for learning and tests. For PostgreSQL, add the driver and set the connection:

xml
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>
properties
spring.datasource.url=jdbc:postgresql://localhost:5432/shop
spring.datasource.username=shop
spring.datasource.password=${DB_PASSWORD}
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.open-in-view=false
ddl-auto Effect Use
create-drop Create tables at start, drop at stop Default for embedded databases (H2)
update Try to alter tables to match entities Quick experiments only
validate Check that tables match entities; change nothing Production, with migrations (Flyway)
none Do nothing Production

In production, never let Hibernate change the schema; use migrations (the Relationships, paging and migrations lesson). And set spring.jpa.open-in-view=false: the default keeps a database connection open while the response is rendered, and Spring Boot logs a warning about it.

Seeing the SQL

properties
logging.level.org.hibernate.SQL=debug
Output
select p1_0.id,p1_0.category,p1_0.name,p1_0.price from product p1_0 where p1_0.id=?
delete from product where id=?

Always watch the SQL while developing: it's how you catch slow or repeated queries.

Practice

  1. Add findTop3ByCategoryOrderByPriceDesc and expose it as GET /api/products/top?category=….
  2. Add a @Query that returns the total stock value, sum(p.price * p.stock).
  3. Add a restock(Long id, int amount) service method that increases the stock inside a transaction, without calling save.
✎ Check your understanding

1.What does extending JpaRepository<Product, Long> give you?

2.What query does findByCategoryAndStockGreaterThan(c, n) run?

3.In a @Transactional method, why doesn't update need to call save()?

← Beans and dependency injection