Sometimes, no matter how many features you try to apply, it seems impossible to get Spring Data JPA to apply every thing you’d like to a query before it is sent to the
3.0.0-SNAPSHOT (and targeted for the next milestone release train of Spring Data), you now have the ability to get your hands on the query, right before it’s sent to the
EntityManager and “rewrite” it. That is, you can make any alterations at the last moment.
Check it out below:
Example 1. Declare a QueryRewriter using
- This pure SQL query (thanks to
nativeQuery) will get routed through yet-to-be-defined
MyQueryRewriterbefore the query is invoked.
- This JPQL query will also get routed through the same
MyQueryRewriterbefore it’s handed over to the
You can then write your own ticket, as shown below!
Example 2. Example
Okay, this one is a tad contrived. We are basically changing the name of a particular query’s alias. But you can really do anything you can think of. This hook gives you a chance to change a little (or a lot!).
Just be sure to register an instance
MyQueryRewriter in the application context. Whether you use one of Spring Framework’s
@Component -based annotations, or you supply it through a
@Bean method inside an
@Configuration class, the choice is yours.
QueryRewriter is invoked after any and all checks have been performed by Spring Data JPA. You’re responsible for supplying a valid query to the
But wait…there’s more!
While you can write your
QueryRewriter as a separate bean, it’s also possible to put right inside the repository where it’s used!
Example 3. Repository that provides the
- Have your repository interface extend the
- Plug in the name of your repository into the native query’s
- Plug in the name of your repository into the JPQL query’s
- Override the
rewrite(String,Sort)method and plugin a
defaultvalue, and POOF you’re done!
Fair warning: it’s possible you may need more than one rewriter based on what exactly you’re doing.
Spring Data JPA supports not only Spring’s application context, but CDI-based environments.