`SimpleJpaRepository.existsById(…)` returns `false` when multiple rows exist for the same ID
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
> 0Linstead of== 1L(smaller change) - Change to
existsas suggested in 3814
Note Multiple rows sharing the same identifier does break the contract but the current behavior produces misleading results in such cases.
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.
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.