Reputation: 27
I need to create an interface that extends the JpaRepository where I want to pass a native (select) query
by parameter instead of leaving static within the @Query
annotation. Instead of using @Query (value = "select * from a where a =: a", nativeQuery = true)
I want to use the code sampled below.
public interface MeuRepository extends JpaRepository<MeuEntity, Integer>{
@Query(value = query, nativeQuery = true)
List<MeuEntity> findCustomNativeQuery(String query);
}
Is it possible to do as the code exemplified above? How?
Upvotes: 1
Views: 5186
Reputation: 32517
If you MUST use native queries then do it with custom implementation.
public interface MeuRepositoryCustom {
List<MeuEntity> findCustomNativeQuery(String query);
}
then
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();
}
}
finally your repository interface
public interface MeuRepository extends JpaRepository<MeuEntity, Integer>, MCustomRepository{
}
Notice that naming is crucial here, as custom interface has to be named ***Custom
and its implementation has to be ***Impl
For more information https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html point 1.3
Here is newer version of documentation
Upvotes: 2