Java

Java

Made by DeepSource

Use existsById instead of findById to check for the existence of an entity JAVA-W1090

Anti-pattern
Major

Use existsById() instead of findById() if you are calling findById() for the sole purpose of checking for the existence of an entity in the repository.

This issue is raised when the Java analyzer detects a usage of findById() where the returned value is only used in a null check.

Bad Practice

if (repository.findById(idValue) != null) {
    // do some operation with the id.
}

Recommended

Use the existsById method to check for the presence of an entity in the repository instead.

if (repository.existsById(idValue)) {
    // do some operation with the id.
}

If your repository definition has no existsById method, consider adding it in.

// In the repository interface
    boolean existsById(<your ID type here> id);