A loop queries a repository once per element, so the database is asked once per row instead of once

tx0/java:query-in-loopstrictwarningperformance/iodepth fastperformance

What it finds

A loop that asks a repository for one row per element sends one query per element: for (Order o : orders) { customers.findById(o.getCustomerId()); } makes a round trip to the database for every order, the pattern known as N+1 queries. It is fast on a test database with ten rows and slow in production with ten thousand. One query for all elements, such as findAllById(ids), a join, or a fetch join in the first query, does the same work in one round trip.

Reported, in a file that imports Spring, JPA or MyBatis, is a call of a method whose name starts with find, get, select, query, load, count, exists or fetch on a field whose type is named ...Repository, ...Dao or ...Mapper (but not a mapper of objects such as Jackson's ObjectMapper), in the body of a loop over the elements of a collection (for (x : xs)) or of a lambda passed to forEach, within the same method. Calls that return a lazy reference without a query, such as getReferenceById, are left alone, and so are counting for, while and do loops, which usually walk up parents or page through results on purpose, and test code.

From the rule's source, query_in_loop.rs.

Example from the rule's tests
import com.fasterxml.jackson.databind.ObjectMapper;import java.util.List;import org.springframework.stereotype.Service; @Serviceclass Orders {  private final CustomerRepository customers;  private final OrderMapper orderMapper;  private final ObjectMapper json;   Orders(CustomerRepository customers, OrderMapper orderMapper, ObjectMapper json) {    this.customers = customers;    this.orderMapper = orderMapper;    this.json = json;  }   void report(List<Order> orders) {    for (Order o : customers.findAllOrders()) {      customers.findById(o.customerId());tx0 reports: this query runs once for every element of the loop      customers.getReferenceById(o.customerId());      json.getTypeFactory();    }    orders.forEach(o -> orderMapper.selectLines(o.id()));tx0 reports: once for every element    int i = 0;    while (i < orders.size()) {      customers.save(orders.get(i));      i++;    }    customers.findById(1L);  }   record Order(long id, long customerId) {}}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:query-in-loop" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:query-in-loop] reason="..."

tx0 explain tx0/java:query-in-loop shows the same in the terminal. Found a false positive? Report it.