High-performance Java Persistence.pdf
An e-commerce site saw timeouts during Black Friday. The team found that loading a ShoppingCart entity triggered lazy loading of CartItem, Product, Discount, and Inventory across 50 queries. After applying the "Dynamic Fetching" strategies from High-performance Java Persistence.pdf, they reduced the transaction to 2 queries and a single JOIN FETCH. Time per request dropped from 4 seconds to 50ms.
This is the classic trap. You fetch a list of Post entities, and then for each post, you access the post.comments list. If lazy loading is enabled (as it should be), Hibernate triggers a separate SQL query for every post to fetch its comments.
The Fix: Use JOIN FETCH in your JPQL queries to fetch the associated collections in a single query.
// Bad: N+1 queries List<Post> posts = entityManager.createQuery("select p from Post p", Post.class).getResultList();
// Good: 1 query List<Post> posts = entityManager.createQuery( "select p from Post p left join fetch p.comments", Post.class) .getResultList();High-performance Java Persistence.pdf
To give you a taste of the practical value inside the High-performance Java Persistence.pdf, consider the Bulk Update dilemma.
The naïve approach (Bad):
List<Post> posts = entityManager.createQuery("from Post", Post.class).getResultList();
for(Post p : posts)
p.setStatus(Status.OLD);
// Hibernate will send UPDATE 1, UPDATE 2, UPDATE 3...
The book’s recommended approach (Good):
int updatedEntities = entityManager.createQuery(
"update Post set status = :newStatus where createdOn < :date")
.setParameter("newStatus", Status.OLD)
.setParameter("date", LocalDate.now().minusDays(30))
.executeUpdate();
// Sends 1 SQL statement.
The PDF spends pages explaining why the first loop kills your performance (transaction bloat, row lock escalation, and network round trips) and how to identify this using the datasource-proxy logger, a tool the author created.
The Persistence Context (the First Level Cache) is designed to provide automatic dirty checking and ensure referential integrity. However, it can easily become a memory hog. An e-commerce site saw timeouts during Black Friday
It is important to note that while many search for free copies, the author (Vlad Mihalcea) actively maintains this as a commercial/paid resource. However, a wealth of information is legally available:
Pro tip: Even if you cannot obtain the full PDF immediately, the author has published a series of "Mastering JPA" articles on his blog, which serve as a condensed version of the book's core concepts.
