spring-data-jpa icon indicating copy to clipboard operation
spring-data-jpa copied to clipboard

`SimpleJpaRepository.existsById(…)` returns `false` when multiple rows exist for the same ID

Open SebOnTheWeb opened this issue 7 months ago • 2 comments

This happens because the current implementation in SimpleJpaRepository uses a COUNT query and compares the result to 1L:

return query.getSingleResult() == 1L;

If more than one row matches the given ID, the count will be greater than 1, causing the method to return false.

I can provide replication details if needed.

Proposal Consider one of the following

  • Change to > 0L instead of == 1L (smaller change)
  • Change to exists as suggested in 3814

Note Multiple rows sharing the same identifier does break the contract but the current behavior produces misleading results in such cases.

SebOnTheWeb avatar Apr 08 '26 15:04 SebOnTheWeb

Hi, I'd like to work on this would a PR be welcome?
The fix would be changing == 1L to > 0L in SimpleJpaRepository at lines 388 and 407, so existsById correctly returns true regardless of how many rows match the given ID.

chanani avatar Apr 09 '26 01:04 chanani

There's quite a bit of an issue here with the underlying assumption of identifiers being unique. This is obviously not the case here and practically speaking, it's an unsupported use case which will fall apart once trying to interact with an entity through by-id lookup.

We can certainly check for a row count greater zero and make this specific case work by being lenient.

mp911de avatar Apr 09 '26 15:04 mp911de