Reputation: 881
Is there any way to pass a native query as a variable?
I want to use something like that
@Component
public interface MyRepository extends JpaRepository<MyClass, long>{
@Query(nativeQuery = true, value = query)
List<Sapf> find(String query);
}
Upvotes: 2
Views: 1589
Reputation: 14411
You need a custom repository to solve your problem. According to the Spring Data documentation you start with an interface:
public interface MyRepositoryCustom {
List<Sapf> find(String query);
}
Then you need to implement it. You need to inject the entity manager so you can execute the native query:
public class MyRepositoryCustomImpl implements MyRepositoryCustom {
@PersistenceContext(unitName = "yourPersistenceUnitName")
private EntityManager em;
List<Sapf> find(String query) {
Query query = em.createNativeQuery(query, Sapf.class);
return query.getResultList();
}
}
Finally, you extend the created interface in your Spring Data Repository and the rest is done by the framework.
@Repository
public interface MyRepository extends JpaRepository<MyClass, long>, MyRepositoryCustom {
}
Depending on your Spring configuration, your custom implementation should be used automatically. If not, check out the documentation to adjust you settings.
Upvotes: 2