Menu

1 / 2

Stop counting N+1 queries by eye — one rule finds them all

DEV Community: java·SongRenShuo·7 days ago
#VVZAYTqY
#devtojava#devto#dev#thread#shape
Long article (1431 words) — no AI summary yet.
Reading 0:00
15s threshold

A list endpoint loads 50 orders. One query fetches the page. Then, to render each order's owner, the code fires one more lookup per row — fifty statements that read SELECT id, username, avatar FROM sys_user WHERE id = ? and differ only in the bound id. One screen for the user, fifty-one queries for the database.

Locally this is invisible: the test table has six rows, every query takes about a millisecond, and the log reads as noise. In staging, where the data starts to look real, response time grows linearly with row count, and by the time somebody goes looking, the log is a few hundred lines of statements that all look alike.

The trigger is almost always a loop touching a lazy relation — collection nesting in a MyBatis mapper, or a JPA @OneToMany that loads on first access. Each line involved was individually reasonable; the bug exists only in their sum.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.