[spring, jpa, repository, xml]
This is the post #5 of the series "Querying your Spring Data JPA Repository".
And this is a quick one.
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.
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 working app is here (wait for Heroku to load the app, it takes a few seconds on the free tier).
There's only this (and I promptly reverted afterwards).