【问题标题】:Pass native query per parameter to JpaRepository Interface将每个参数的本机查询传递给 JpaRepository 接口
【发布时间】:2018-02-15 15:00:33
【问题描述】:

我需要创建一个扩展 JpaRepository 的接口,我想在其中通过参数传递本机(选择)query,而不是在@Query 注释中保留静态。而不是使用@Query (value = "select * from a where a =: a", nativeQuery = true),我想使用下面的示例代码。

 public interface MeuRepository extends JpaRepository<MeuEntity, Integer>{

     @Query(value = query, nativeQuery = true)
     List<MeuEntity> findCustomNativeQuery(String query);
 }

是否可以按照上面示例的代码进行操作? 怎么样?

【问题讨论】:

    标签: java spring spring-data-jpa


    【解决方案1】:

    如果您必须使用本机查询,请使用自定义实现。

    public interface  MeuRepositoryCustom {
      List<MeuEntity> findCustomNativeQuery(String query);
    }
    

    然后

    public class  MeuRepositoryImpl implements  MeuRepositoryCustom{
    
    @PeristenceContext
    private EntityManager em; // here you will get plain EntityManager impl.
    
    List<MeuEntity> findCustomNativeQuery(String query){
    
     TypedQuery<MeuEntity> q=em.createQuery(query,MeuEntity.class)
     return q.getResultList();
    }
    }
    

    最后是你的存储库界面

    public interface MeuRepository extends JpaRepository<MeuEntity, Integer>, MCustomRepository{
    
     }
    

    请注意,此处命名至关重要,因为自定义接口必须命名为 ***Custom,其实现必须为 ***Impl

    更多信息https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html点1.3

    这是更新版本的文档

    https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations

    【讨论】:

    • 我需要为我的所有存储库创建一个***Custom***Impl
    • Spring 数据的整个想法是摆脱创建自定义的普通查询,并且当您想要返回时,是的。威胁它为向后兼容机制;)但您始终可以使您的自定义接口通用正确并让所有存储库扩展它。
    • 我需要自定义where,所以我通过Map&lt;Key, String&gt; 并动态构建where 以组成select。明白吗?
    • 是的,我会为此使用CriteriaQuery,看起来这是唯一的选择,在自定义 repo 实现中执行此操作。如果您有这样的复杂标准,这就是要走的路。
    • 我不知道怎么做,我需要一步一步来
    猜你喜欢
    • 2019-07-26
    • 2017-12-06
    • 2019-11-11
    • 2012-08-29
    • 2018-03-08
    • 1970-01-01
    • 2017-09-27
    • 2014-08-23
    • 1970-01-01
    相关资源
    最近更新 更多