Spring Data JPA: entities, repositories and query methods

Spring Data JPA turns an interface into a working data access layer: you declare methods, and it writes the queries. Underneath sit JPA and Hibernate, with their own rules about managed entities, flushing and lazy loading. This page explains both layers and runs every example against an in-memory H2 database, with the SQL Hibernate sends.

Contents

How Spring Data JPA fits together

Three layers sit between your code and the database, and each one does a different job:

  • JPA (Jakarta Persistence): a specification. It defines annotations such as @Entity and @Id, the EntityManager API, and the JPQL query language. It contains no implementation.
  • Hibernate: the JPA implementation Spring Boot uses. It maps entity classes to tables, generates SQL, and keeps a persistence context: a per-transaction cache of loaded entities that it compares against the database at flush time, writing back whatever changed.
  • Spring Data JPA: a layer on top of the EntityManager. You declare a repository interface, and at startup Spring Data creates a proxy for it. Built-in methods such as save and findById go to a class called SimpleJpaRepository; methods you declare are turned into queries from their names or from a @Query annotation.

Most surprises on this page come from the Hibernate layer, not from Spring Data: an update that is never written, a save() that returns a different object, a collection that cannot be read. Knowing which layer does what makes them easy to explain.

A repository interface extends one of the Spring Data base interfaces. Each adds methods to the one before it:

Spring Data repository interfaces
InterfaceAddsBest for
Repository<T, ID>Nothing; a marker for scanningExposing only the methods you declare yourself
CrudRepositorysave, findById, findAll, count, delete..., returning IterableBasic CRUD in any Spring Data module
ListCrudRepository (Spring Data 3.0)The same methods returning ListCRUD without converting Iterable
PagingAndSortingRepositoryfindAll(Sort), findAll(Pageable)Paged lists
JpaRepositoryAll of the above with List results, plus flush, saveAndFlush, deleteAllInBatch, getReferenceById and query by exampleThe usual choice with JPA

The examples use Spring Boot 4.1 with spring-boot-starter-data-jpa, which brings Spring Data JPA 4.1 and Hibernate 7.4, and the H2 database. Each program is a complete Spring Boot application that starts, runs its example and shuts down. Several of them print the SQL that Hibernate sends, using the org.hibernate.SQL logger switched on after startup so that the table creation is not shown.

A first entity and repository

A Book entity with a generated id and an empty repository interface is enough to store and read rows. The program also asks what the repository bean really is:

Java
package jpa.first;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.math.BigDecimal;
import java.util.Map;
import org.springframework.aop.support.AopUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.jpa.repository.JpaRepository;

@SpringBootApplication
public class FirstRepository {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(FirstRepository.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.pattern.console", "%logger{0}: %msg%n"));
        try (var context = app.run(args)) {
            LoggingSystem.get(FirstRepository.class.getClassLoader())
                    .setLogLevel("org.hibernate.SQL", LogLevel.DEBUG);
            BookRepository books = context.getBean(BookRepository.class);
            System.out.println("Repository is a proxy: " + AopUtils.isAopProxy(books));
            System.out.println("Implementation: " + AopUtils.getTargetClass(books).getName());

            Book saved = books.save(new Book("Dune", "Herbert", new BigDecimal("9.99")));
            books.save(new Book("Emma", "Austen", new BigDecimal("7.50")));
            System.out.println("Saved with id " + saved.getId());
            System.out.println("count() = " + books.count());
            System.out.println("findById(1) = " + books.findById(1L));
            System.out.println("findById(99) = " + books.findById(99L));
            books.deleteById(1L);
            System.out.println("After deleteById(1): " + books.findAll());
        }
    }
}

@Entity
class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String author;
    private BigDecimal price;

    protected Book() {
    }

    Book(String title, String author, BigDecimal price) {
        this.title = title;
        this.author = author;
        this.price = price;
    }

    Long getId() {
        return id;
    }

    @Override
    public String toString() {
        return "Book[" + id + ", " + title + ", " + author + ", " + price + "]";
    }
}

interface BookRepository extends JpaRepository<Book, Long> {
}
Output
Repository is a proxy: true
Implementation: org.springframework.data.jpa.repository.support.SimpleJpaRepository
SQL: select next value for book_seq
SQL: insert into book (author,price,title,id) values (?,?,?,?)
SQL: select next value for book_seq
SQL: insert into book (author,price,title,id) values (?,?,?,?)
Saved with id 1
SQL: select count(*) from book b1_0
count() = 2
SQL: select b1_0.id,b1_0.author,b1_0.price,b1_0.title from book b1_0 where b1_0.id=?
findById(1) = Optional[Book[1, Dune, Herbert, 9.99]]
SQL: select b1_0.id,b1_0.author,b1_0.price,b1_0.title from book b1_0 where b1_0.id=?
findById(99) = Optional.empty
SQL: select b1_0.id,b1_0.author,b1_0.price,b1_0.title from book b1_0 where b1_0.id=?
SQL: delete from book where id=?
SQL: select b1_0.id,b1_0.author,b1_0.price,b1_0.title from book b1_0
After deleteById(1): [Book[2, Emma, Austen, 7.50]]
SQL: drop table if exists book cascade 
SQL: drop sequence if exists book_seq
  • The repository is a proxy, and the object doing the work behind it is SimpleJpaRepository. Every JpaRepository in an application shares that one implementation class.
  • @GeneratedValue with no strategy means AUTO, which Hibernate maps to a database sequence called book_seq with an increment of 50. The first two inserts each read the sequence; after that Hibernate hands out ids from memory until the block of 50 runs out. With five books, the sequence is still read only twice.
  • findById(99) returns Optional.empty rather than throwing, so the caller decides what a missing row means.
  • deleteById(1) runs a SELECT and then a DELETE: Spring Data loads the entity and passes it to EntityManager.remove, so entity callbacks and cascades run. That costs an extra query per row.
  • The two drop statements at the end come from shutdown. Spring Boot sets spring.jpa.hibernate.ddl-auto to create-drop for an embedded database such as H2, and to none otherwise.

Spring Boot found the entity and the repository because they are in the package of the @SpringBootApplication class or below it. The entity needs a no-argument constructor, which may be protected, because Hibernate creates instances by reflection when it reads rows.

Derived query methods

A method named findBy... is parsed into a query: the words after By name entity properties, joined by keywords such as And, Or, LessThan, Containing and OrderBy. Four books by two authors give each method something to filter:

Java
package jpa.derived;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.jpa.repository.JpaRepository;

@SpringBootApplication
public class DerivedQueries {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(DerivedQueries.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.pattern.console", "%logger{0}: %msg%n"));
        try (var context = app.run(args)) {
            LoggingSystem.get(DerivedQueries.class.getClassLoader())
                    .setLogLevel("org.hibernate.SQL", LogLevel.DEBUG);
            BookRepository books = context.getBean(BookRepository.class);
            books.saveAll(List.of(
                    new Book("Dune", "Herbert", "9.99"),
                    new Book("Dune Messiah", "Herbert", "8.99"),
                    new Book("Emma", "Austen", "7.50"),
                    new Book("Persuasion", "Austen", "6.25")));
            System.out.println("-- findByAuthor(\"Austen\")");
            System.out.println(books.findByAuthor("Austen"));
            System.out.println("-- findByTitleContainingIgnoreCase(\"dune\")");
            System.out.println(books.findByTitleContainingIgnoreCase("dune"));
            System.out.println("-- findByPriceLessThanOrderByPriceDesc(9.00)");
            System.out.println(books.findByPriceLessThanOrderByPriceDesc(new BigDecimal("9.00")));
            System.out.println("-- findFirstByAuthorOrderByPriceAsc(\"Herbert\")");
            System.out.println(books.findFirstByAuthorOrderByPriceAsc("Herbert"));
            System.out.println("-- countByAuthor(\"Herbert\")");
            System.out.println(books.countByAuthor("Herbert"));
            System.out.println("-- existsByTitle(\"Ulysses\")");
            System.out.println(books.existsByTitle("Ulysses"));
        }
    }
}

@Entity
class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String author;
    private BigDecimal price;

    protected Book() {
    }

    Book(String title, String author, String price) {
        this.title = title;
        this.author = author;
        this.price = new BigDecimal(price);
    }

    @Override
    public String toString() {
        return title + " (" + price + ")";
    }
}

interface BookRepository extends JpaRepository<Book, Long> {
    List<Book> findByAuthor(String author);

    List<Book> findByTitleContainingIgnoreCase(String fragment);

    List<Book> findByPriceLessThanOrderByPriceDesc(BigDecimal max);

    Optional<Book> findFirstByAuthorOrderByPriceAsc(String author);

    long countByAuthor(String author);

    boolean existsByTitle(String title);
}
Output
SQL: select next value for book_seq
SQL: select next value for book_seq
SQL: insert into book (author,price,title,id) values (?,?,?,?)
SQL: insert into book (author,price,title,id) values (?,?,?,?)
SQL: insert into book (author,price,title,id) values (?,?,?,?)
SQL: insert into book (author,price,title,id) values (?,?,?,?)
-- findByAuthor("Austen")
SQL: select b1_0.id,b1_0.author,b1_0.price,b1_0.title from book b1_0 where b1_0.author=?
[Emma (7.50), Persuasion (6.25)]
-- findByTitleContainingIgnoreCase("dune")
SQL: select b1_0.id,b1_0.author,b1_0.price,b1_0.title from book b1_0 where upper(b1_0.title) like upper(?) escape '\'
[Dune (9.99), Dune Messiah (8.99)]
-- findByPriceLessThanOrderByPriceDesc(9.00)
SQL: select b1_0.id,b1_0.author,b1_0.price,b1_0.title from book b1_0 where b1_0.price<? order by b1_0.price desc
[Dune Messiah (8.99), Emma (7.50), Persuasion (6.25)]
-- findFirstByAuthorOrderByPriceAsc("Herbert")
SQL: select b1_0.id,b1_0.author,b1_0.price,b1_0.title from book b1_0 where b1_0.author=? order by b1_0.price fetch first ? rows only
Optional[Dune Messiah (8.99)]
-- countByAuthor("Herbert")
SQL: select count(b1_0.id) from book b1_0 where b1_0.author=?
2
-- existsByTitle("Ulysses")
SQL: select b1_0.id from book b1_0 where b1_0.title=? fetch first ? rows only
false
SQL: drop table if exists book cascade 
SQL: drop sequence if exists book_seq
  • findByTitleContainingIgnoreCase("dune") became upper(title) like upper(?). Spring Data adds the % wildcards around the value and escapes any % or _ the caller passes in.
  • findFirstByAuthorOrderByPriceAsc added fetch first ? rows only, so the database returns one row, the cheapest Herbert book at 8.99.
  • countBy produced a count query, and existsBy a query limited to one row that reads only the id. Neither loads whole entities.
  • The return type shapes the query too: Optional for at most one result, List for many, long and boolean for the count and exists forms.

Derived queries are checked when the application starts, not when they are called. A method that names a property the entity does not have stops the whole application:

Java
package jpa.badname;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;

@SpringBootApplication
public class BadMethodName {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(BadMethodName.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF"));
        try {
            app.run(args).close();
            System.out.println("started");
        } catch (RuntimeException e) {
            Throwable cause = e;
            while (cause.getCause() != null) {
                cause = cause.getCause();
            }
            System.out.println("Startup failed: " + e.getClass().getSimpleName());
            System.out.println("Root cause: " + cause.getClass().getSimpleName());
            System.out.println(cause.getMessage());
        }
    }
}

@Entity
class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String author;
}

interface BookRepository extends JpaRepository<Book, Long> {
    List<Book> findByAutor(String author);
}
Output
Startup failed: BeanCreationException
Root cause: PropertyReferenceException
No property 'autor' found for type 'Book'; Did you mean 'author'

The misspelt findByAutor failed with PropertyReferenceException, and the message even suggests author. Failing at startup is useful: a typo is found by the first test that starts the context, not by a user. Names longer than three or four conditions become hard to read, and that is the point to switch to @Query.

@Query: JPQL, native SQL and bulk updates

@Query takes the query text directly. JPQL queries work on entity and property names, native queries on table and column names. The second half of this program shows the trap with bulk updates: one book is already loaded when the update runs.

Java
package jpa.query;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.support.TransactionTemplate;

@SpringBootApplication
public class QueryMethods {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(QueryMethods.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            BookRepository books = context.getBean(BookRepository.class);
            TransactionTemplate tx = context.getBean(TransactionTemplate.class);
            books.saveAll(List.of(
                    new Book("Dune", "Herbert", "9.99"),
                    new Book("Emma", "Austen", "7.50"),
                    new Book("Persuasion", "Austen", "6.25")));

            System.out.println("JPQL   : " + books.priceBetween(new BigDecimal("7"),
                    new BigDecimal("10")));
            System.out.println("Native : " + books.titlesByAuthor("Austen"));

            tx.executeWithoutResult(status -> {
                Book emma = books.findByTitle("Emma");
                System.out.println("Before update, Emma costs " + emma.getPrice());
                int rows = books.raisePrices(new BigDecimal("1.10"));
                System.out.println("raisePrices updated " + rows + " rows");
                System.out.println("findByTitle after update: "
                        + books.findByTitle("Emma").getPrice());
                System.out.println("same object as before? "
                        + (emma == books.findByTitle("Emma")));
            });
            tx.executeWithoutResult(status -> System.out.println(
                    "New transaction sees: " + books.findByTitle("Emma").getPrice()));

            tx.executeWithoutResult(status -> {
                Book emma = books.findByTitle("Emma");
                books.raisePricesAndClear(new BigDecimal("1.10"));
                System.out.println("With clearAutomatically: "
                        + books.findByTitle("Emma").getPrice()
                        + " (old object still says " + emma.getPrice() + ")");
            });
        }
    }
}

@Entity
class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String author;
    private BigDecimal price;

    protected Book() {
    }

    Book(String title, String author, String price) {
        this.title = title;
        this.author = author;
        this.price = new BigDecimal(price);
    }

    BigDecimal getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return title;
    }
}

interface BookRepository extends JpaRepository<Book, Long> {
    Book findByTitle(String title);

    @Query("select b from Book b where b.price between :low and :high order by b.price")
    List<Book> priceBetween(@Param("low") BigDecimal low, @Param("high") BigDecimal high);

    @Query(value = "SELECT title FROM book WHERE author = ?1 ORDER BY title",
            nativeQuery = true)
    List<String> titlesByAuthor(String author);

    @Modifying
    @Query("update Book b set b.price = b.price * :factor")
    int raisePrices(@Param("factor") BigDecimal factor);

    @Modifying(clearAutomatically = true)
    @Query("update Book b set b.price = b.price * :factor")
    int raisePricesAndClear(@Param("factor") BigDecimal factor);
}
Output
JPQL   : [Emma, Dune]
Native : [Emma, Persuasion]
Before update, Emma costs 7.50
raisePrices updated 3 rows
findByTitle after update: 7.50
same object as before? true
New transaction sees: 8.25
With clearAutomatically: 9.08 (old object still says 8.25)
  • The JPQL query uses named parameters bound with @Param, and returns entities. The native query uses the positional ?1 and returns a plain List<String> of titles.
  • raisePrices needs @Modifying, because it is an UPDATE rather than a SELECT. It returned 3, the number of rows changed, and it ran straight in the database, bypassing the persistence context.
  • That is the trap: Emma was already loaded, so findByTitle after the update returned the same object, still at 7.50, although the database held 8.25. Hibernate ran the query but kept its own copy of a row it was already managing.
  • A new transaction has a new persistence context, so it read 8.25 from the database.
  • clearAutomatically = true empties the persistence context after the update, so the next query read the fresh 9.08 (8.25 times 1.10, rounded to the column's two decimals). The object loaded before the update was detached and still says 8.25.

A bulk update also skips everything that works on entities: @Version checks, entity callbacks, auditing and cascades. Use it for large changes where that is acceptable, and load entities one by one when it is not. A @Modifying method must run inside a transaction; here TransactionTemplate provides one. Called without one, raisePrices fails with InvalidDataAccessApiUsageException: "No active transaction for update or delete query". Annotating the repository method with @Transactional also works.

Paging and sorting

A Pageable parameter adds limit and offset to a query, and Sort adds order by. Seven tickets split into pages of three give a full page, a second full page and a short last page:

Java
package jpa.paging;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;

@SpringBootApplication
public class Paging {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Paging.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.pattern.console", "%logger{0}: %msg%n"));
        try (var context = app.run(args)) {
            LoggingSystem.get(Paging.class.getClassLoader())
                    .setLogLevel("org.hibernate.SQL", LogLevel.DEBUG);
            TicketRepository tickets = context.getBean(TicketRepository.class);
            tickets.saveAll(IntStream.rangeClosed(1, 7)
                    .mapToObj(i -> new Ticket("T" + i, i % 3 == 0 ? "HIGH" : "LOW"))
                    .toList());

            Pageable second = PageRequest.of(1, 3, Sort.by("code").descending());
            Page<Ticket> page = tickets.findAll(second);
            System.out.println("Page " + page.getNumber() + " of " + page.getTotalPages()
                    + ", " + page.getTotalElements() + " tickets: " + page.getContent());

            Slice<Ticket> slice = tickets.findByPriority("LOW", PageRequest.of(0, 3));
            System.out.println("Slice: " + slice.getContent() + ", hasNext = "
                    + slice.hasNext());

            List<Ticket> sorted = tickets.findByPriority("HIGH",
                    Sort.by(Sort.Order.desc("code")));
            System.out.println("Sorted list: " + sorted);
        }
    }
}

@Entity
class Ticket {
    @Id
    @GeneratedValue
    private Long id;
    private String code;
    private String priority;

    protected Ticket() {
    }

    Ticket(String code, String priority) {
        this.code = code;
        this.priority = priority;
    }

    @Override
    public String toString() {
        return code;
    }
}

interface TicketRepository extends JpaRepository<Ticket, Long> {
    Slice<Ticket> findByPriority(String priority, Pageable pageable);

    List<Ticket> findByPriority(String priority, Sort sort);
}
Output
SQL: select next value for ticket_seq
SQL: select next value for ticket_seq
SQL: insert into ticket (code,priority,id) values (?,?,?)
SQL: insert into ticket (code,priority,id) values (?,?,?)
SQL: insert into ticket (code,priority,id) values (?,?,?)
SQL: insert into ticket (code,priority,id) values (?,?,?)
SQL: insert into ticket (code,priority,id) values (?,?,?)
SQL: insert into ticket (code,priority,id) values (?,?,?)
SQL: insert into ticket (code,priority,id) values (?,?,?)
SQL: select t1_0.id,t1_0.code,t1_0.priority from ticket t1_0 order by t1_0.code desc offset ? rows fetch first ? rows only
SQL: select count(t1_0.id) from ticket t1_0
Page 1 of 3, 7 tickets: [T4, T3, T2]
SQL: select t1_0.id,t1_0.code,t1_0.priority from ticket t1_0 where t1_0.priority=? fetch first ? rows only
Slice: [T1, T2, T4], hasNext = true
SQL: select t1_0.id,t1_0.code,t1_0.priority from ticket t1_0 where t1_0.priority=? order by t1_0.code desc
Sorted list: [T6, T3]
SQL: drop table if exists ticket cascade 
SQL: drop sequence if exists ticket_seq
  • PageRequest.of(1, 3, ...) asks for the second page, because page numbers start at 0. Sorted by code descending, the order is T7 to T1, so the second page is T4, T3, T2.
  • A Page also reports the total, 7 tickets on 3 pages, and that needs the second query, select count(...). On a large table, that count can cost more than the page itself.
  • A Slice skips the count. Spring Data asks for one row more than the page size, and hasNext is true when that extra row exists. That suits "load more" buttons and infinite scrolling, where the total is not shown.
  • Sort on its own gives a sorted List with no limit. Sort properties are entity property names, checked against the entity, so Sort.by("code") is safe from SQL injection; an unknown name fails.

Offset paging gets slower for deep pages, because the database still reads and discards all the rows before the offset. For large tables, keyset scrolling with ScrollPosition avoids that; it is shown on the Spring Data JPA advanced page.

What save() really does

save() is not a plain insert or update. It asks whether the entity is new, which by default means its id is null, then calls EntityManager.persist for new entities and merge for the others. And inside a transaction, changes to loaded entities are written without any save() at all. This program shows all four cases:

Java
package jpa.save;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.support.TransactionTemplate;

@SpringBootApplication
public class SaveSemantics {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(SaveSemantics.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.pattern.console", "%logger{0}: %msg%n"));
        try (var context = app.run(args)) {
            LoggingSystem.get(SaveSemantics.class.getClassLoader())
                    .setLogLevel("org.hibernate.SQL", LogLevel.DEBUG);
            AccountRepository accounts = context.getBean(AccountRepository.class);
            TransactionTemplate tx = context.getBean(TransactionTemplate.class);

            System.out.println("1. save() a new entity (id is null)");
            Account fresh = new Account("ann", 100);
            Account returned = accounts.save(fresh);
            System.out.println("   same instance returned: " + (fresh == returned));

            System.out.println("2. save() a detached entity (id is set)");
            Account detached = new Account("ann", 250);
            detached.setId(returned.getId());
            Account merged = accounts.save(detached);
            System.out.println("   same instance returned: " + (detached == merged));

            System.out.println("3. change a managed entity, no save() call");
            tx.executeWithoutResult(status -> {
                Account managed = accounts.findById(returned.getId()).orElseThrow();
                managed.setBalance(300);
            });
            System.out.println("   balance in database: "
                    + accounts.findById(returned.getId()).orElseThrow().getBalance());

            System.out.println("4. change an entity outside a transaction, no save() call");
            Account loaded = accounts.findById(returned.getId()).orElseThrow();
            loaded.setBalance(999);
            System.out.println("   balance in database: "
                    + accounts.findById(returned.getId()).orElseThrow().getBalance());
        }
    }
}

@Entity
class Account {
    @Id
    @GeneratedValue
    private Long id;
    private String owner;
    private int balance;

    protected Account() {
    }

    Account(String owner, int balance) {
        this.owner = owner;
        this.balance = balance;
    }

    Long getId() {
        return id;
    }

    void setId(Long id) {
        this.id = id;
    }

    int getBalance() {
        return balance;
    }

    void setBalance(int balance) {
        this.balance = balance;
    }

    @Override
    public String toString() {
        return owner + ": " + balance;
    }
}

interface AccountRepository extends JpaRepository<Account, Long> {
}
Output
1. save() a new entity (id is null)
SQL: select next value for account_seq
SQL: insert into account (balance,owner,id) values (?,?,?)
   same instance returned: true
2. save() a detached entity (id is set)
SQL: select a1_0.id,a1_0.balance,a1_0.owner from account a1_0 where a1_0.id=?
SQL: update account set balance=?,owner=? where id=?
   same instance returned: false
3. change a managed entity, no save() call
SQL: select a1_0.id,a1_0.balance,a1_0.owner from account a1_0 where a1_0.id=?
SQL: update account set balance=?,owner=? where id=?
SQL: select a1_0.id,a1_0.balance,a1_0.owner from account a1_0 where a1_0.id=?
   balance in database: 300
4. change an entity outside a transaction, no save() call
SQL: select a1_0.id,a1_0.balance,a1_0.owner from account a1_0 where a1_0.id=?
SQL: select a1_0.id,a1_0.balance,a1_0.owner from account a1_0 where a1_0.id=?
   balance in database: 300
SQL: drop table if exists account cascade 
SQL: drop sequence if exists account_seq
  • Case 1: the id was null, so persist ran an insert, and save returned the same object it was given.
  • Case 2: the object had an id, so merge first ran a SELECT to load the row, copied the new state onto the loaded entity, and updated it. The returned object is a different instance. Code that keeps using the argument instead of the return value works with a detached copy, so always use what save returns.
  • Case 3: the entity was loaded inside a transaction and changed, with no save() call. At commit, Hibernate compared it with the state it had loaded (dirty checking) and wrote the update. The balance is 300.
  • Case 4: outside a transaction, findById ran in its own short transaction, and the entity was detached as soon as it returned. Changing it afterwards wrote nothing; the balance is still 300, not 999.

Case 2 also explains why entities with ids you assign yourself, such as a UUID set in the constructor, cost an extra SELECT on every insert: they never look new, so save merges them. Adding a @Version field of a wrapper type such as Long fixes this, because Spring Data then treats a null version as new. Implementing Persistable lets the entity decide in isNew().

Relationships and lazy loading

An author with many books is the usual one-to-many pair. The Book side owns the foreign key with @ManyToOne, and the Author side maps it back with mappedBy. The program then reads the relationships outside and inside a transaction:

Java
package jpa.relations;

import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.support.TransactionTemplate;

@SpringBootApplication
public class Relationships {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Relationships.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            AuthorRepository authors = context.getBean(AuthorRepository.class);
            BookRepository books = context.getBean(BookRepository.class);
            TransactionTemplate tx = context.getBean(TransactionTemplate.class);

            Author austen = new Author("Austen");
            austen.addBook(new Book("Emma"));
            austen.addBook(new Book("Persuasion"));
            Long id = authors.save(austen).getId();
            System.out.println("Saved one author, books in table: " + books.count());

            Author loaded = authors.findById(id).orElseThrow();
            System.out.println("Loaded author: " + loaded.getName());
            try {
                System.out.println(loaded.getBooks().size());
            } catch (RuntimeException e) {
                System.out.println("Outside a transaction: " + e.getClass().getSimpleName());
            }

            int count = tx.execute(status ->
                    authors.findById(id).orElseThrow().getBooks().size());
            System.out.println("Inside a transaction: " + count + " books");

            Book emma = books.findByTitle("Emma");
            Author proxy = emma.getAuthor();
            System.out.println("Book's author is a " + proxy.getClass().getSimpleName());
            try {
                System.out.println(proxy.getName());
            } catch (RuntimeException e) {
                System.out.println("Reading its name: " + e.getMessage());
            }
        }
    }
}

@Entity
class Author {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Book> books = new ArrayList<>();

    protected Author() {
    }

    Author(String name) {
        this.name = name;
    }

    void addBook(Book book) {
        books.add(book);
        book.setAuthor(this);
    }

    Long getId() {
        return id;
    }

    String getName() {
        return name;
    }

    List<Book> getBooks() {
        return books;
    }
}

@Entity
class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;

    @ManyToOne(fetch = FetchType.LAZY)
    private Author author;

    protected Book() {
    }

    Book(String title) {
        this.title = title;
    }

    Author getAuthor() {
        return author;
    }

    void setAuthor(Author author) {
        this.author = author;
    }
}

interface AuthorRepository extends JpaRepository<Author, Long> {
}

interface BookRepository extends JpaRepository<Book, Long> {
    Book findByTitle(String title);
}
Output
Saved one author, books in table: 2
Loaded author: Austen
Outside a transaction: LazyInitializationException
Inside a transaction: 2 books
Book's author is a Author$HibernateProxy
Reading its name: Could not initialize proxy [jpa.relations.Author#1] - no session
  • Saving only the author stored both books, because cascade = CascadeType.ALL passes the save on to the collection. orphanRemoval = true would also delete a book removed from the list.
  • A @OneToMany collection is lazy by default. The author was loaded in findById's own transaction, so reading getBooks() afterwards threw LazyInitializationException: the session that could run the query had closed.
  • Inside one transaction, the same call ran a second query and returned 2.
  • The book's @ManyToOne was marked LAZY, so getAuthor() returned an Author$HibernateProxy, a generated subclass with only the id filled in. Reading its name outside a transaction failed the same way.

Without fetch = FetchType.LAZY, a @ManyToOne is eager, and every book query also loads its author, often with one extra query per book. Mark to-one relationships lazy, and load what a use case needs with a fetch join or an entity graph inside the transaction. The advanced page measures these choices.

In a Spring MVC application, spring.jpa.open-in-view is true by default: the EntityManager stays open for the whole web request, so lazy loading in a controller or a view works. Spring Boot logs a warning about it at startup, because it hides extra queries and keeps a database connection for longer. Many teams set it to false.

Setting it up in Spring Boot 4

Add spring-boot-starter-data-jpa and a JDBC driver. Spring Boot then creates the DataSource, the EntityManagerFactory, a JpaTransactionManager, and a repository bean for every repository interface it finds. The properties used most often:

Common Spring Data JPA properties
PropertyDefaultUse
spring.datasource.url, username, passwordAn embedded database if one is on the classpathWhere to connect
spring.jpa.hibernate.ddl-autocreate-drop for embedded databases, otherwise nonevalidate in production, with a migration tool creating the schema
spring.jpa.show-sqlfalsePrints SQL to standard output; the org.hibernate.SQL logger at DEBUG does the same through logging
spring.jpa.open-in-viewtrueSet to false to keep lazy loading inside the service layer
spring.jpa.properties.*NonePasses any Hibernate setting through, such as hibernate.jdbc.batch_size

Spring Boot 4 split its auto-configuration into modules, which moved some classes. @EntityScan, for entities outside the application's package, is now org.springframework.boot.persistence.autoconfigure.EntityScan; in Spring Boot 3 it was in org.springframework.boot.autoconfigure.domain. Since Spring Boot 3, all JPA annotations come from jakarta.persistence, not javax.persistence.

Leave ddl-auto at none or validate for real databases. Letting Hibernate alter a production schema gives you no review, no history and no way back; Flyway and Liquibase manage schema changes as versioned scripts instead.

Choosing a query style

Which kind of repository method to use
NeedUse
Load, save or delete by idThe built-in JpaRepository methods
A filter on one to three propertiesA derived query method
Joins, grouping, or a name that grows too long@Query with JPQL
Database-specific SQL, such as window functions@Query(nativeQuery = true)
Changing many rows in one statement@Modifying @Query, with clearAutomatically if entities are already loaded
Lists shown page by page with a totalPageable returning Page
"Load more" lists without a totalPageable returning Slice
Search forms with optional filtersSpecifications or a custom fragment, see custom repositories
Reading only a few columnsProjections, see Spring Data JPA advanced

Whatever the query style, keep the transaction boundary in the service layer. The @Transactional page explains how that boundary works. Auditing and soft delete build on the entity lifecycle shown here, and the H2 page covers the database used in these examples.