Search code examples
javaspringspring-data

What is the difference between findById() and existsById() in Spring Data 2.0?


Spring Data 2.0 JpaRepository: difference between findById() and existsById()

  • Which scenario do we use findById() and existsById() methods?

Solution

  • According to documentation:

    existsById(ID id) - returns boolean

    Returns whether an entity with the given id exists.

    findById(ID id) - returns Optional (object)

    Retrieves an entity by its id.

    Simple as that - findById() returns object, which you are searching for, existsById() returns true/false whether or not entity exists in repository.