(Spring/JpaRepository ) Dynamic @Query, when Inheriting methods of JpaRepository from BaseEntityRepository to SubEntityRepository
(此贴继续讨论,重要部分都在这里重复:
(Spring/JpaRepository) 从 BaseEntityRepository 到 SubEntityRepository 继承 JpaRepository 的方法)
假设我们有以下实体:
1 2 | @Entity public class BaseEntity { } @Entity public class SubEntity extends BaseEntity { } |
和以下 JpaRepository 实现:
1 2 3 4 5 6 7 8 | public interface BaseEntityRepository<T, I> extends JpaRepository<TableWithId, Long> { @Query("SELECT t FROM BaseEntity t WHERE id = :id") Optional< T > getById(@Param("id") Long id); @Query("SELECT t FROM BaseEntity t WHERE customField = :customField") List< T > findByCustomField(@Param("customField") String customField); } |
现在对于子实体,我有另一个仓库:
1 | public interface SubEntityRepository extends BaseEntityRepository<SubEntity, Long> {} |
JPA?? 会知道@Query 中的"BaseEntity" 必须替换为"SubEntity",为什么?
如果"否",如何做我想做的事情的最佳方式?
你需要使用 SPEL
1 2 | @Query("SELECT T FROM #{#entityName} T WHERE T.id = :id") Optional< T > getById(@Param("id") Long id); |