2

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);
}
1
  • If you're building that query dynamically, then no, it's not possible. You need to use a custom repository implementation and pass your query to the entity manager. Commented Dec 4, 2015 at 7:44

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

The name of your persistence unit that you have in your Spring configuration. If you have only one persistence unit in you application, you can omit this parameter.
I got error "No property find found for type Sapf!" when I extends MyRepository. When I use MyRepositoryCustomImpl as a @Component and inject it to other class the methon fine(String query) it works fine.
Is the Sapf class an entity? If not then you'll need to define a custom mapping using @SqlResultSetMapping
Yes, Sapf class is entity
The problem might be connected with the fact that methods started with find are treated specially by Spring Data. Try renaming the method find to something else and see if it helps.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.