Skip to content

Count Vs Exists (ARCH4063)

Key java.orm.count-vs-exists · Severity info · Category orm

Using count() > 0 to test for presence counts all matches; exists() stops at the first row. Use existsBy... for existence tests.

if (orderRepository.countByUserId(userId) > 0) {
// counts them all
}
if (orderRepository.existsByUserId(userId)) {
// short-circuits at the first row
}

Use a short-circuiting exists() query instead of count > 0 for existence checks.