Spring存储库接口(interface): query methods by type

标签 spring spring-data spring-data-jpa

我想知道是否可以使用 Spring 的 query methods 指定特定的子类型.

例如,如果有 MailUserChatUser , 两个 extend UserInheritanceType.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/

相关文章:

spring - Spring Security 上的组和 acl

java - 提供列表框的更好方法

java - 尝试获取对象列表时应该使用通用类型还是通配符?

java - 如何从 QueryDSL 检索列表/结果

java - Spring Boot如何编辑实体

java - Spring 4 网络 - java.lang.IllegalArgumentException : No matching constant for [0]

java - 使用映射的 JPA 集合

Elasticsearch 和 SpringData : FindAll and OrderBy

java - 为什么SimpleJdbcCall会忽略@Transactional注解

spring - 休息 : Extending CrudRepository for self-referencing entities throws an exception