(Spring/JpaRepository ) 动态@Query,当将 JpaRepository 的方法从 BaseEntityRepository 继承到 SubEntityRepository 时 [英] (Spring/JpaRepository ) Dynamic @Query, when Inheriting methods of JpaRepository from BaseEntityRepository to SubEntityRepository

查看:16
本文介绍了(Spring/JpaRepository ) 动态@Query,当将 JpaRepository 的方法从 BaseEntityRepository 继承到 SubEntityRepository 时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(这篇文章继续讨论,重要的部分都在这里重复:(Spring/JpaRepository) 从 JpaRepository 继承 JpaRepository 的方法子实体存储库)

假设我们有以下实体:

@Entity public class BaseEntity { }
@Entity public class SubEntity extends BaseEntity { }

以及以下 JpaRepository 实现:

and the following JpaRepository implemenations:

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);
}

现在对于子实体,我有另一个仓库:

Now for the SubEntity I have another repo:

public interface SubEntityRepository extends BaseEntityRepository<SubEntity, Long> {}

JPA 会知道@Query 中的BaseEntity"必须替换为SubEntity"吗?为什么?如果不",如何做我想做的事情的最佳方式?

Will JPA know that in @Query "BaseEntity" must be replaced by "SubEntity" and why? If "no", how would be the best way to do what I want?

推荐答案

你需要使用SPEL

@Query("SELECT T FROM #{#entityName} T WHERE T.id = :id")
Optional<T> getById(@Param("id") Long id);

这篇关于(Spring/JpaRepository ) 动态@Query,当将 JpaRepository 的方法从 BaseEntityRepository 继承到 SubEntityRepository 时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆