我想知道是否可以使用 Spring 的 query methods 指定特定的子类型.
例如,如果有 MailUser
和 ChatUser
, 两个 extend User
与 InheritanceType.SINGLE_TABLE
- 我可以找到所有MailUser
s 与 PersonRepository
?
或者我可以找到所有User
s 不包括所有 MailUser
s 在多个类 extend User
的场景中?
public interface PersonRepository extends Repository<User, Long> {
List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);
...
}
最佳答案
您不能通过基于方法名称的自动查询创建来做到这一点,Spring Data 不支持它(请参阅 here 了解支持的表达式)。但是,您可以 use @Query
手动指定 JPQL 查询并使用 TYPE(entity)
WHERE
中的运算符子句缩小到特定的实体类型。见 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
关于Spring存储库接口(interface): query methods by type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29607899/