Performance1 - SpotBugsExtensionForSpringFrameWork/CS5098 GitHub Wiki
Bug Pattern Name: JPA_N_PLUS_ONE_PROBLEM
Short Description: Spring JPA N+1 Problem
Recommended fetch plan in JPA is lazy loading which loads every association and collection on demand, lazily. This fetch plan will most likely result in too many SQL statements, each loading only one small piece of data (minimized SQL query should be our goal for efficiency). This will lead to n+1 selects problems. On the other side, using eager loading can make fewer SQL statements, the chunk of data loaded in memory would be so huge which can lead to less optimization for searching data (also consider Cartesian product problem).
The N+1 query problem happens when the data access framework executed N additional SQL statements to fetch the same data that could have been retrieved when executing the primary SQL query.
Example code
List<Item> items = em.createQuery("select i from Item i").getResultList();
// select * from ITEM
for( Item item :items) {
assertNotNull(item.getSeller().getUsername());
// select * from USERS where ID = ?
}
Code description: You see one SQL SELECT to load the Item entity instances. Then, while you iterate through all the items, retrieving each User requires an additional SELECT. This amounts to one query for the Item plus n queries depending on how many items you have and whether a particular User is selling more than one Item. Obviously, this is a very inefficient strategy if you know you’ll access the seller of each Item.
With what you know so far, you might be tempted to change the default fetch plan in your mappings and put a FetchType.EAGER on your seller or bids associations. But doing so can lead to our next topic: the Cartesian product problem.
- Join Fetch
- @EntityGraph
- https://vladmihalcea.com/n-plus-1-query-problem/
- https://stackoverflow.com/questions/2990799/difference-between-fetchtype-lazy-and-eager-in-java-persistence-api
- https://www.baeldung.com/hibernate-lazy-eager-loading
- https://tech.asimio.net/2020/11/06/Preventing-N-plus-1-select-problem-using-Spring-Data-JPA-EntityGraph.html
- https://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem-in-orm-object-relational-mapping/97253
- https://stackoverflow.com/questions/32453989/what-is-the-solution-for-the-n1-issue-in-jpa-and-hibernate
- Java Persistence with Hibernate 2nd ed. (296 page)
- https://stackoverflow.com/questions/24257449/how-do-i-use-annotations-to-define-different-types-of-relationships-in-hibernate/24257450#24257450