Spring 存储库接口:按类型查询方法
Spring repository interface: query methods by type
我想知道是否可以使用弹簧 query methods 指定特定的子类型。
例如,如果有 MailUser
和 ChatUser
,extend User
和 InheritanceType.SINGLE_TABLE
- 我能找到所有 MailUser
和 PersonRepository
?
或者在多个 类 extend User
的情况下,我可以找到所有 User
排除所有 MailUser
吗?
public interface PersonRepository extends Repository<User, Long> {
List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);
...
}
您不能使用基于方法名称的自动查询创建,Spring数据不支持它(参见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 实体类型表达式:
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
我想知道是否可以使用弹簧 query methods 指定特定的子类型。
例如,如果有 MailUser
和 ChatUser
,extend User
和 InheritanceType.SINGLE_TABLE
- 我能找到所有 MailUser
和 PersonRepository
?
或者在多个 类 extend User
的情况下,我可以找到所有 User
排除所有 MailUser
吗?
public interface PersonRepository extends Repository<User, Long> {
List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);
...
}
您不能使用基于方法名称的自动查询创建,Spring数据不支持它(参见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 实体类型表达式:
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