An endpoint returning 100 orders fires 101 SQL statements. What is happening and how do you confirm it?
basicOne query loads the orders, then each order's lazy association (customer, items) is initialized with its own SELECT when accessed: 1 + N queries. Confirm by logging SQL and counting statements per request.
spring.jpa.show-sql=trueis crude (stdout, no bind values); preferlogging.level.org.hibernate.SQL=DEBUGandlogging.level.org.hibernate.orm.jdbc.bind=TRACE(Hibernate 6).- Enable
hibernate.generate_statisticsand assertgetPrepareStatementCount()in tests, or use datasource-proxy.
- Does making the association EAGER fix it? No, a JPQL query still loads parents first and then fires one select per parent for the eager association.
- Does
findByIdhave N+1? No,findcan join eager associations in a single query.