Using JPQL on orm.xml file with Spring Data JPA
[spring, jpa, repository, xml]
You'll have a better experience reading in DEV
Click here to continue reading this post there >>
However, if you want to know more about the project to mirror my posts from DEV here (and why), go ahead and read more.
You can continue to read here too, it's up to you... =]
This is the post #5 of the series "Querying your Spring Data JPA Repository".
And this is a quick one.
Remember our JPQL?
Yeah, what if for some reason you want to externalize the query to a XML file. Why, you ask? Well, I'm not sure. More on that at the end of this post.
Just put it on a orm.xml file!
The file must be at
<?xml version="1.0" encoding="UTF-8"?> <entity-mappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm" version="2.2"> <named-query name="Restaurant.activeGrabngoByCity"> <query>from Restaurant r where r.active = true and r.grabngo = true and r.city like concat('%', :city, '%')</query> </named-query> <!-- You can have more... <named-query name="Restaurant.otherMethodName"> <query>from Restaurant where whatever ... </query> </named-query> --> </entity-mappings>
As always, let's highlight some things:
entity-mappingstag must be exactly what you see here. Just copy and paste this part.
- The attribute
nameon the tag
named-queryspecifies the method the query will relate to. Whenever the method is called this JPA query is executed.
- The query had to go over a small change, did you notice? We added a
concatto form the last portion of the
whereclause. Without it an
unexpected token: %error would be thrown.
You'd also have to change other things, like replace
>, which is the way to use those characters in XML.
I can think of one benefit which is the ability to change the query without recompiling the application. This is questionable, though, but... well... it's possible.
To be honest here, there's way more you can do on this file related to persistence and JPA. In fact, you could configure everything JPA-related on this file and ditch annotations. Everybody, though, is moving out from XML-based configuration to Annotations-based configuration.
Yet, this is still something to learn, I believe. I just like how complicated things get over time, and this is one manifestation of this complexity.
The example app
The working app is here (wait for Heroku to load the app, it takes a few seconds on the free tier).
Commits related to this post
There's only this (and I promptly reverted afterwards).
brunodrugowick / jpa-queries-blog-post
A demo project for a blog post about (Spring Data) JPA.