I wonder if it is possible to specify a specific subtype with springs' query methods.
For example, if there is a MailUser
and ChatUser
, both extend User
with InheritanceType.SINGLE_TABLE
- can I find all MailUser
s with the PersonRepository
?
Or can I find all User
s excluding all MailUser
s in a scenario where multiple classes extend User
?
public interface PersonRepository extends Repository<User, Long> {
List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);
...
}
You cannot do it with the automatic query creation based on the method names, Spring Data does not support it (see here for the supported expressions). However, you can use @Query
to specify a JPQL query by hand and use the TYPE(entity)
operator in the WHERE
clause to narrow down to a particular entity type. See JPA spec 4.6.17.5 Entity Type Expressions:
An entity type expression can be used to restrict query polymorphism. The
TYPE
operator returns the exact type of the argument.[...]
Examples:
SELECT e FROM Employee e WHERE TYPE(e) IN (Exempt, Contractor) SELECT e FROM Employee e WHERE TYPE(e) IN (:empType1, :empType2) SELECT e FROM Employee e WHERE TYPE(e) IN :empTypes SELECT TYPE(e) FROM Employee e WHERE TYPE(e) <> Exempt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With