DEV Community

Cover image for Using JPQL on orm.xml file with Spring Data JPA
Bruno Drugowick
Bruno Drugowick

Posted on

Using JPQL on orm.xml file with Spring Data JPA

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 resources/META-INF/orm.xml:

<?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>

Enter fullscreen mode Exit fullscreen mode

As always, let's highlight some things:

  • The entity-mappings tag must be exactly what you see here. Just copy and paste this part.
  • The attribute name on the tag named-query specifies 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 concat to 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 < with &lt; and > with &gt;, which is the way to use those characters in XML.

The benefit

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).

GitHub logo brunodrugowick / jpa-queries-blog-post

A demo project for a blog post about (Spring Data) JPA.

Top comments (0)