Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring repository interface: query methods by type

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 MailUsers with the PersonRepository?

Or can I find all Users excluding all MailUsers in a scenario where multiple classes extend User?

public interface PersonRepository extends Repository<User, Long> {

  List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);
...
}
like image 702
Stefan K. Avatar asked Oct 19 '22 14:10

Stefan K.


1 Answers

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
like image 145
Adam Michalik Avatar answered Oct 29 '22 14:10

Adam Michalik