Home > Enterprise >  Why does spring use findById before deleteById
Why does spring use findById before deleteById

Time:09-29

In this "The best way to write a Spring Data Exists Query" article is mentioned how NOT to write exists query. One of two mentioned NOT TODO`s is:

emulating existence with a findBy query

Optional<Post> findBySlug(String slug);

The reason mentioned is:

... waste of resources ... to send the entity result set over the network to the JDBC Driver

My main question is then: Why does Spring Data JPA SimpleJpaRepository.java validate if an entity exists with findById() method?

this.delete(this.findById(id).orElseThrow(() -> {
  return new EmptyResultDataAccessException(...);
}));

}

Second question is: Should I validate if an entity exists in database before calling deleteById method, if SimpleJpaRepository does validate it, or is it redundant? My general delete method:

  public void delete(String id) {
    if (!userRepository.existsById(id)) {
      throw new ObjectNotFoundException();
    }
    userRepository.deleteById(id);
  }

CodePudding user response:

Why does Spring Data JPA SimpleJpaRepository.java validate if an entity exists with findById() method?

Because JPA will load the entity anyway. It needs to do that since it has to fire lifecycle events which require the entity.

Should I validate if an entity exists in database before calling deleteById method, if SimpleJpaRepository does validate it, or is it redundant?

Currently this is redundant. I'd recommend to still do it though since the behavior of the delete operations will change and they will no longer throw exceptions when nothing gets found to be deleted.

I would recommend though to actually use findById instead of existsById because if it get found Spring Data JPA will execute a findById anyway. And if you did that before already it will be just a lookup in the first level cache. But if you only did an exists check another SQL statement has to be executed.

  • Related