Spring Repository的@Query中使用@MappedSuperclass的通用查询问题
你当前查询失效的核心原因是BaseDocument被标注为@MappedSuperclass,不属于JPA规范定义的实体类型,JPQL不允许在FROM子句中直接引用非实体类。
可行解决方案
你可以直接使用Spring Data JPA内置的SpEL表达式#{#entityName}实现通用查询,该表达式会在运行时自动替换为当前调用该方法的子Repository对应的实际实体类名,无需在子Repository做任何额外配置。
修改后的代码如下:
@NoRepositoryBean public interface DocumentRepository<T extends BaseDocument> extends JpaRepository<T, Long> { @Query(value = "FROM #{#entityName} bd WHERE (bd.createdAt IS NULL OR :to IS NULL OR bd.createdAt < :to) AND (bd.deletedAt IS NULL OR :from IS NULL OR bd.deletedAt > :from)") Iterable<T> findAllActiveBetween(OffsetDateTime from, OffsetDateTime to); } @MappedSuperclass @Where(clause="deleted_at IS NULL") abstract public class BaseDocument { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private OffsetDateTime createdAt; private OffsetDateTime deletedAt; }
额外说明
你已经在BaseDocument上添加了@Where(clause="deleted_at IS NULL")注解,默认所有查询都会自动过滤已软删的记录,如果该方法不需要包含已删除数据,可以简化查询语句中的deletedAt相关判断逻辑,减少冗余条件。
内容的提问来源于stack exchange,提问作者Milan Majer
相关产品推荐
相关产品推荐

