I’m working with Spring Data repositories and came across the following statement in the documentation:
Following that path can easily lead to confusion and is discouraged as you will quickly hit type limits if the ID type and the type of your Id property deviate.
I understand that the repository interface requires specifying the domain type and its identifier type as generic parameters. However, I’m unclear about the phrase “hit type limits.”
Does this mean I’ll encounter compile-time type mismatches or runtime errors if the declared ID type in the repository doesn’t match the type of the property named “Id” in my domain object?
What exactly are “type limits” in this context? Is it related to the limitations of Java’s generic type system, or does it refer to a different kind of constraint?
The standard CrudRepository
provides method like
Optional<T> findById(ID id)
It also allows for derived methods like
SomeType findBySomeProperty(ID id)
here SomeType
could be T
, Optional<T>
, List<T>
and many more and someProperty
is some property of your entity.
Now you could define a domain model, where you have a property named id
which is not the ID of the entity.
Query derivation wont work for findById
since it is already declared to work with the actual ID, no matter what it is named.
What you then could do is create your own findById
using a @Query
annotation.
But if you do this and the ID property is of a different type than your id
property (or your custom findById
should return a different type than Optional<T>
) you might easily run into situations where
a) a different findById
is called than the one you intend.
b) the code does not compile, because the types result in a variant of overloading/overwriting of method that is not acceptable.