Reputation: 1061
JPA @NamedQuery is translated to SQL only once when application is deployed and generated SQL is cached. EntityManager.createQuery translates query every time our method is called.
What Spring-data-jpa is doing with query defined in @Query annotation? Is it translated to SQL once during deployment (like NamedQuery) or translated every time (like dynamic query) ?
Upvotes: 2
Views: 826
Reputation: 83061
Spring Data JPA calls EntityManager.createQuery(…)
for every invocation of a query method annotated with @Query
. The reason for that is quite simple: the Query
instances returned by the EntityManager
are not thread-safe and actually stateful as they contain bound parameter information.
That said, most of the JPA persistence provider perform some kind of text-based query caching anyway so that they basically build the actual SQL query once for a certain JPQL query and reuse the former on subsequent invocations.
As an interesting side note, when we started building the support for @Query
in 2008 we looked into possibilities to rather register the manually declared queries as named queries with JPA. Unfortunately there wasn't - and up until today - there's no way to manually register a named query programmatically via the JPA.
Upvotes: 3