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
and@Entity , the@Id API, and the JPQL query language. It contains no implementation.EntityManager - 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
. You declare a repository interface, and at startup Spring Data creates a proxy for it. Built-in methods such asEntityManager andsave go to a class calledfindById ; methods you declare are turned into queries from their names or from aSimpleJpaRepository annotation.@Query
Most surprises on this page come from the Hibernate layer, not from Spring Data: an update that is never written, a save()
A repository interface extends one of the Spring Data base interfaces. Each adds methods to the one before it:
| Interface | Adds | Best for |
|---|---|---|
Repository<T, ID> | Nothing; a marker for scanning | Exposing only the methods you declare yourself |
CrudRepository | savefindByIdfindAllcountdelete...Iterable | Basic CRUD in any Spring Data module |
ListCrudRepository | The same methods returning List | CRUD without converting Iterable |
PagingAndSortingRepository | findAll(Sort)findAll(Pageable) | Paged lists |
JpaRepository | All of the above with ListflushsaveAndFlushdeleteAllInBatchgetReferenceById | The usual choice with JPA |
The examples use Spring Boot 4.1 with spring-boot-starter-data-jpaorg.hibernate.SQL
A first entity and repository
A Book
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> {
}
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
. EverySimpleJpaRepository in an application shares that one implementation class.JpaRepository with no strategy means@GeneratedValue , which Hibernate maps to a database sequence calledAUTO 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.book_seq returnsfindById(99) rather than throwing, so the caller decides what a missing row means.Optional.empty runs adeleteById(1) and then aSELECT : Spring Data loads the entity and passes it toDELETE , so entity callbacks and cascades run. That costs an extra query per row.EntityManager.remove- The two
statements at the end come from shutdown. Spring Boot setsdrop tospring.jpa.hibernate.ddl-auto for an embedded database such as H2, and tocreate-drop otherwise.none
Spring Boot found the entity and the repository because they are in the package of the @SpringBootApplicationprotected
Derived query methods
A method named findBy...ByAndOrLessThanContainingOrderBy
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);
}
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
becamefindByTitleContainingIgnoreCase("dune") . Spring Data adds theupper(title) like upper(?) wildcards around the value and escapes any% or% the caller passes in._ addedfindFirstByAuthorOrderByPriceAsc , so the database returns one row, the cheapest Herbert book at 8.99.fetch first ? rows only produced acountBy query, andcount a query limited to one row that reads only the id. Neither loads whole entities.existsBy- The return type shapes the query too:
for at most one result,Optional for many,List andlong for the count and exists forms.boolean
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:
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);
}
Startup failed: BeanCreationException
Root cause: PropertyReferenceException
No property 'autor' found for type 'Book'; Did you mean 'author'
The misspelt findByAutorPropertyReferenceExceptionauthor@Query
@Query: JPQL, native SQL and bulk updates
@Query
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);
}
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
, and returns entities. The native query uses the positional@Param and returns a plain?1 of titles.List<String> needsraisePrices , because it is an@Modifying rather than aUPDATE . It returned 3, the number of rows changed, and it ran straight in the database, bypassing the persistence context.SELECT- That is the trap: Emma was already loaded, so
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.findByTitle - A new transaction has a new persistence context, so it read 8.25 from the database.
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.clearAutomatically = true
A bulk update also skips everything that works on entities: @Version@ModifyingTransactionTemplateraisePricesInvalidDataAccessApiUsageException@Transactional
Paging and sorting
A PageableSortorder by
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);
}
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
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.PageRequest.of(1, 3, ...)- A
also reports the total, 7 tickets on 3 pages, and that needs the second query,Page . On a large table, that count can cost more than the page itself.select count(...) - A
skips the count. Spring Data asks for one row more than the page size, andSlice is true when that extra row exists. That suits "load more" buttons and infinite scrolling, where the total is not shown.hasNext on its own gives a sortedSort with no limit. Sort properties are entity property names, checked against the entity, soList is safe from SQL injection; an unknown name fails.Sort.by("code")
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
What save() really does
save()nullEntityManager.persistmergesave()
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> {
}
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
, sonull ran an insert, andpersist returned the same object it was given.save - Case 2: the object had an id, so
first ran amerge 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 whatSELECT returns.save - Case 3: the entity was loaded inside a transaction and changed, with no
call. At commit, Hibernate compared it with the state it had loaded (dirty checking) and wrote the update. The balance is 300.save() - Case 4: outside a transaction,
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.findById
Case 2 also explains why entities with ids you assign yourself, such as a UUID set in the constructor, cost an extra SELECTsave@VersionLongnullPersistableisNew()
Relationships and lazy loading
An author with many books is the usual one-to-many pair. The Book@ManyToOneAuthormappedBy
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);
}
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
passes the save on to the collection.cascade = CascadeType.ALL would also delete a book removed from the list.orphanRemoval = true - A
collection is lazy by default. The author was loaded in@OneToMany 's own transaction, so readingfindById afterwards threwgetBooks() : the session that could run the query had closed.LazyInitializationException - Inside one transaction, the same call ran a second query and returned 2.
- The book's
was marked@ManyToOne , soLAZY returned angetAuthor() , a generated subclass with only the id filled in. Reading its name outside a transaction failed the same way.Author$HibernateProxy
Without fetch = FetchType.LAZY@ManyToOne
In a Spring MVC application, spring.jpa.open-in-viewtrueEntityManagerfalse
Setting it up in Spring Boot 4
Add spring-boot-starter-data-jpaDataSourceEntityManagerFactoryJpaTransactionManager
| Property | Default | Use |
|---|---|---|
spring.datasource.urlusernamepassword | An embedded database if one is on the classpath | Where to connect |
spring.jpa.hibernate.ddl-auto | create-dropnone | validate |
spring.jpa.show-sql | false | Prints SQL to standard output; the org.hibernate.SQLDEBUG |
spring.jpa.open-in-view | true | Set to false |
spring.jpa.properties.* | None | Passes any Hibernate setting through, such as hibernate.jdbc.batch_size |
Spring Boot 4 split its auto-configuration into modules, which moved some classes. @EntityScanorg.springframework.boot.persistence.autoconfigure.EntityScanorg.springframework.boot.autoconfigure.domainjakarta.persistencejavax.persistence
Leave ddl-autononevalidate
Choosing a query style
| Need | Use |
|---|---|
| Load, save or delete by id | The built-in JpaRepository |
| A filter on one to three properties | A derived query method |
| Joins, grouping, or a name that grows too long | @Query |
| Database-specific SQL, such as window functions | @Query(nativeQuery = true) |
| Changing many rows in one statement | @Modifying @QueryclearAutomatically |
| Lists shown page by page with a total | PageablePage |
| "Load more" lists without a total | PageableSlice |
| Search forms with optional filters | Specifications or a custom fragment, see |
| Reading only a few columns | Projections, see |
Whatever the query style, keep the transaction boundary in the service layer. The