Why is this an issue?

Using Spring repository calls inside loops or stream operations (e.g., peek, forEach, forEachOrdered, map) triggers unnecessary multiple access to the database instead of a single batch call. This leads to unnecessary CPU overhead, increased database load and higher energy consumption.

Examples

Noncompliant

private final List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

List<Employee> employees = new ArrayList<>();

for (Integer id: ids) {
    Optional<Employee> employee = employeeRepository.findById(id); // Noncompliant
    if (employee.isPresent()) {
        employees.add(employee.get());
    }
}
List<Employee> employees = new ArrayList<>();
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
stream.forEach(id -> {
    Optional<Employee> employee = employeeRepository.findById(id); // Noncompliant
    if (employee.isPresent()) {
        employees.add(employee.get());
    }
});

Compliant

private final List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Employee> employees = employeeRepository.findAllById(ids);
List<Integer> ids = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).toList();
List<Employee> employees = employeeRepository.findAllById(ids);