将每个参数的本机查询传递给JpaRepository接口

时间:2017-05-15 18:42:59

标签: java spring spring-data-jpa

我需要创建一个扩展JpaRepository的接口,我希望通过参数传递本机(select)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);
 }

是否可以像上面举例说明的那样做? 怎么样?

1 个答案:

答案 0 :(得分:2)

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

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