0

I called CrudRepository#findById two times inside the same method, it displayed in console one select statement. why the second select statement doesn't displayed in the second method call.

here is the service code:

@Service
@RequiredArgsConstructor
public class AccountService {
    private final AccountReporitory accountReporitory;

    public void find() {
        final Account account1 = accountReporitory.findById(1L).get();
        final Account account2 = accountReporitory.findById(1L).get();
    }
}

here is the repository code:

public interface AccountReporitory extends JpaRepository<Account, Long> {
}
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • You have the answer in your question title. It seems you already know what is going on. – Jens Schauder May 18 '21 at 08:18
  • Does this answer your question? [Spring JpaRepository is not returning updated data](https://stackoverflow.com/questions/23339274/spring-jparepository-is-not-returning-updated-data) – Jens Schauder May 18 '21 at 08:21

1 Answers1

1

When you make the first call to findById(1L) the resulting entity is placed in the session's first level cache. Any succeeding calls to findById() with the same id in the same session will result in the entity manager retrieving the entity from the first level cache instead of performing a database query. This is one of the primary purposes of the first level cache.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Lee Greiner
  • 649
  • 3
  • 6